topvillas's avatar

Route Resource Conundrum

I wonder if anybody's encountered a situation like this and if there's a way to get around it.

In my web routes I have a staff resource ...

Route::resource('staff', 'StaffController');

And in my api routes I have the same thing.

The reason being that the web resource index method serves up a blade template the the api resource index will send a list of staff members. Then I can handle pagination, sorting and searching on the client.

The problem comes when, in my navigation, I use route('staff.index'). It will return the api route.

0 likes
5 replies
ModestasV's avatar

Hey,

Well, first of all - you should prefix your api routes with a api. to separate them. The reason for this is to avoid the confusion and issues with naming/acessing wrong routes.

To do that, look at example:

Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
    Route::get('/', ['as' => 'index', 'uses' => 'AccountController@index']);
    Route::get('connect', ['as' => 'connect', 'uses' = > 'AccountController@connect']);
});

Where account. will be the prefix for next route names.

topvillas's avatar

Routes in the api routes file are automatically prefixed with api.

The problem is that resource routes don't seem to have any way of knowing where they are.

So having the same resource in the api and web doubles up on the named routes and causes a problem for the route() helper.

ModestasV's avatar

@topvillas No. You got something confused there :)

'prefix' => 'api' !== 'as' => 'api.'

The prefix is for browser URL.

The as is for the names of the routes.

Example:

protected function mapApiRoutes()
    {
        Route::group([
            'namespace' => $this->namespace,
            'prefix'    => 'api', // This will add prefix to the route URL
        ], function ($router) {
            require base_path('routes/api.php');
        });

        Route::group([
            'namespace' => $this->namespace,
            'prefix'    => 'api', // This will add prefix to the route URL
            'as'        => 'api.', // This will add prefix to the route names. Ex.: api.users.create
        ], function ($router) {
            require base_path('routes/api.php');
        });
    }
topvillas's avatar

No no. I'm talking about resource based routes. Their names are being doubled up because Laravel has no way of knowing whether the resource group is sitting in the api or the web routes files.

But anyway, it doesn't matter. I'm just using the plain url. But for obvious reasons I'd prefer it I could use named routes.

topvillas's avatar

Well, I just had to double facepalm when it struck me that I could just put resource routes in a group with 'as'.

Thanks for the help @ModestasV

Please or to participate in this conversation.