Demers94
6 months ago

Controllers structure for API and "regular" routes

Posted 6 months ago by Demers94

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', '[email protected]');

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 :

  1. 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', '[email protected]');

    // OffersController.php
    public function index()
    {
        if(request()->isAjax()){
            return Offer::get();
        }

        return view('offers.index');
    }
  1. Call another method on the same controller
    // Offers.vue
    axios.get('/api/offers').then(response => {...})

    // routes/web.php
    Route::get('/offers', '[email protected]');
    Route::get('/api/offers', '[email protected]');

    // OffersController.php
    public function index()
    {
        return view('offers.index');
    }

    public function api()
    {
        return Offer::get();
    }
  1. 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', '[email protected]');
    Route::get('/api/offers', 'Api\[email protected]');

    // 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 sign in or create an account to participate in this conversation.