I'm trying to send 2 variables to FavorisController: {{ Auth::user()->id }} and the id that I have in the URL
This is what I've tried so far
Route:
Route::get('annonce_test/{id}','FavorisController@create' );
My ajax script
$(document).ready(function() {
$('.favoris').click(function(){
var id_user = "{{ Auth::user()->id }}" ;
$.ajax({
url: 'annonce_test/{id}',
type: 'GET',
data: {id: 1, id_user: $id_user},
success: function(data){
alert(Ajouter au Favoris avec succes);
},
error: function(){},
});""
});
});
FavorisController
public function create(Requests $request)
{
$id_annonce = $_GET['id'];
$id_user = $_GET['id_user'];
$query = DB::table('annonce_residentiel_user')
->insertGetId(
array('annonce_residentiel_id' => $id_annonce , 'user_id' => $id_user)
);
}
I got the error trying to get property of non-object {{ Auth::user()->id }}
But is this the correct way to do it? I mean if I have another script for deleting I should chage the url in my ajax script.
Move Auth::user() part from JS script to PHP:
->insertGetId(['annonce_residentiel_id' => $id_annonce , 'user_id' => auth()->user()->id]);
Also, make sure user is authenticated with something like:
if (auth()->check()) {
// Do stuff.
}
Based on your route definition $id is the argument for the create method and to get more data from the ajax call you should use Input::get. Also the route will be activated only when the url in the ajax call has the format of ex: annonce_test/25. check the update to the ajax call.
Route:
Route::get('annonce_test/{id}','FavorisController@create' );
Ajax call:
$(document).ready(function() {
$('.favoris').click(function(){
var id_user = "{{ Auth::user()->id }}" ;
$.ajax({
url: 'annonce_test/'+id_user,
type: 'GET',
data: {id: 1},
success: function(data){
alert(Ajouter au Favoris avec success);
},
error: function(){},
});
});
});
FavorisController:
public function create($id)
{
$id_annonce = Input::get['id'];
$query = DB::table('annonce_residentiel_user')->insertGetId(
array('annonce_residentiel_id' => $id_annonce , 'user_id' => $id));
}