Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Fetch ajax data in route and pass to controller

I'm using Laravel 5 and want to make ajax call to a controller with some data:

 $.ajax({
    url : "/getOrgById",
    data : JSON.stringify({id:1})
})

The routes.php has:

Route::get('/getOrgById', 'HomeController@getOrgById');

HomeController.php:

public function getOrgById($data) {
   //code here fails with message 'Missing argument 1 for HomeController::getOrgById()
}

How can I pass the data from ajax to route and then to controller?

like image 508
Sharon Haim Pour Avatar asked Jul 21 '16 13:07

Sharon Haim Pour


2 Answers

I think the below example is what you're looking for

Route

Route::post('/getOrgById', 'HomeController@getOrgById');

Controller

public function getOrgById(Request $request) {
    $id = $request->input('id');
}

JS

var myJsonData = {id: 1}
$.post('/getOrgById', myJsonData, function(response) {
    //handle response
})
like image 57
saada Avatar answered Oct 03 '22 13:10

saada


You should really look into resourceful controller actions. If you are wanting to fetch an organisation by its ID then you have an organisaiton entity, so create a corresponding organisation controller. This controller can then have a method to show an organisation by on its primary key value:

class OrganisationController
{
    public function show($id)
    {
        return Organisation::findOrFail($id);
    }
}

The route for this would look like:

Route::get('/organisations/{id}', 'OrganisationController@show');

You can then request this route via AJAX like so:

$.ajax({
    method: 'GET',
    url: '/organisations/' + id
});
like image 21
Martin Bean Avatar answered Oct 03 '22 11:10

Martin Bean