Laravel Resource Controllers for using API and non-API

After creating the resource controller PhotosControllerfor the website, which also calls AJAX calls in the API, it looks like the resource controller can be used both on a regular website and as an API.

HTML page is displayed for Photowith id = 1

http://domain.com/photos/1

and javascript uses the following which updates the resource Photoand returns a JSON response

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

Question: Will we have 2 PhotoControllers, one for processing APIs and one for non-APIs?

+3
source share
2 answers

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

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

, Ajax .

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

API:

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

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

:

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

Source: https://habr.com/ru/post/1675751/


All Articles