I personally would go for option 3. You might even use a repository or some class that fetches all the offers which both controllers may use to return the data. Also another advantage of an ApiController is that you might return different results there.
Controllers structure for API and "regular" routes
I'm building an application where the the users can view job offers.
The /offers endpoint calls a controller method that shows the view with all the offers.
Route::get('/offers', 'OffersController@index');
public function index()
{
return view('offers.index');
}
From the front-end, a Vue component makes an API call to fetch the latest offers.
What's the best approach regarding controllers structure for this case?
The way I see it I have three options :
- Call the same controller, same method and return a different response type depending on if the request was made via AJAX or not
// Offers.vue
axios.get('/offers').then(response => {...})
// routes/web.php
Route::get('/offers', 'OffersController@index');
// OffersController.php
public function index()
{
if(request()->isAjax()){
return Offer::get();
}
return view('offers.index');
}
- Call another method on the same controller
// Offers.vue
axios.get('/api/offers').then(response => {...})
// routes/web.php
Route::get('/offers', 'OffersController@index');
Route::get('/api/offers', 'OffersController@api');
// OffersController.php
public function index()
{
return view('offers.index');
}
public function api()
{
return Offer::get();
}
- Call the index() method of a new controller specifically for API routes
// Offers.vue
axios.get('/api/offers').then(response => {...})
// routes/web.php
Route::get('/offers', 'OffersController@index');
Route::get('/api/offers', 'Api\OffersController@index');
// OffersController.php
public function index()
{
return view('offers.index');
}
// Api/OffersController.php
public function index()
{
return Offer::get();
}
What is the best approach in this case?
I like #3 since it allows me to use only CRUD names for my controller methods and I don't have to pollute all the methods with the request()->isAjax() call, but I'm wondering if there would be another solution that would allow me to keep the code in the same place. I'm not convinced it makes sense to use different controllers like that for the same type of data.
Please or to participate in this conversation.