Laravel resource controllers for both API and non-API use

醉酒当歌 提交于 2019-12-06 05:10:39

问题


After creating a resource controller PhotosController for a website that also does AJAX calls to the API, it appears that the resource controller can be used on both the normal website and as the API.

This displays a HTML page for Photo with id = 1

http://domain.com/photos/1

and Javascript uses the following which updates the Photo resource and returns a JSON response

PUT http://domain.com/api/v1/photos/1

Question: Will we have 2 PhotoControllers, one to handle API usage and one for non-API?


回答1:


No. You can have two separate routes point to the same controller and action.

Route::get('/photos/1', 'PhotoController@index');
Route::get('/api/v1/photos/1', 'PhotoController@index');

Then, in your controller methods, you can test whether the request is from Ajax or not.

if (Request::ajax()) {
    // Do some crazy Ajax thing
}



回答2:


I use a route group with prefix for API calls:

Route::resource('venue', 'VenueController');

Route::group(array('prefix' => 'api'), function(){
    Route::resource('venue', 'VenueController', array('only' => array('index', 'show')));
});

Then, in the controller, I use this condition:

if (Route::getCurrentRoute()->getPrefix() == 'api') {
    return Response::json($venues->toArray());
}


来源:https://stackoverflow.com/questions/17899609/laravel-resource-controllers-for-both-api-and-non-api-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!