I want to make a Laravel 5.1 application for web and api's for mobile apps. I want to return json for api request and view for web browser. Currently I have setup different routes and different controllers. In this approach I'm repeating the code. I don't know what is the best approach to design this architecture. Also, I've gone through few similar threads which recommends using angular.js for web browser.
// web controller
Route::resource('product', 'ProductController');
// api controller
Route::group(['prefix' => 'api'], function() {
Route::resource('product', 'APIProductController');
});
You can have 2 basic approaches:
For the 2nd approach you could for example do it like this:
// web controller
Route::resource('product', 'ProductController');
// api controller
Route::group(['prefix' => 'api'], function() {
Route::resource('product', 'ProductController');
});
// and in the ProductController you have
public function index(Request $request)
{
// do some stuff...
if ($request->segment(1) === 'api') { // route prefix was api
// return json
} else {
// return the view
}
}
You could also use $request->wantsJson() method to check on Accept:
header or you could pass a special GET variable (e.g. ?_format=json
) with all API calls to define the response format should be json, as already suggested by @Bogdan Kuštan. IMHO if you already use api prefix on your urls it's more reliable and cleaner to just check on that.
One way would be to use content negotiation approach. You would pass header Accept: application/json
and then Your app would return json formatted response. however some proxy servers do not respect content negotiation, then Your app would break (You can read more why Drupal dropped content negotiation here).
Another possibility is tu use some GET
variable to return requested format, for example: /api/product?format=json
Also You can pass variable from /api
calls:
Route::get('/api/product', ['as' => 'product', function(){
return App::make('ProductController')->index('json');
}]);
public function index($format) {
// Your controller code
if ($format == 'json') {
// return JSON
}
// return HTML
}
Or You can parse URI directly and see if it starts with /API
(do not recommend). My choices would be content negotiation or/and format
GET variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With