4

Is there a way to specify the prefix when getting a route URL by its name in Laravel 5.5? For example,

In routes/web.php

Route::resource('users', 'UserController', ['only' => 'index', 'create', 'edit']);

In routes/api.php

Routes::resource('users', 'UserController', ['only' => 'index', 'store', 'update', 'destroy']);

Both routes to the index methods have the name users.index, as confirmed when calling php artisan route:list. However, the URL for the web route is /users and the URL for the api route is /api/users.

To get the web route URL, I can do route('users.index'). Is there a way to get the URL for the api route using the route name?

Erin
  • 5,315
  • 2
  • 20
  • 36

2 Answers2

3

You can give the resource controller's routes a prefix via the as option:

Route::resource('users', 'UserController', [
    'as' => 'your.prefix',
    'only' => ['index', 'store', 'update', 'destroy'],
]);
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • Thank you for this. I know that I can give custom names, but I was looking for a solution without changing the API at all. – Erin Nov 24 '17 at 14:14
  • 1
    Hello. Spotted an error in answer which gave me headache for some time :) Please correct it: `'only' => ['index', 'store', 'update', 'destroy']` – user8555937 Nov 11 '19 at 16:13
3

In routes/api.php, wrap all routes with the prefix api:

Route::name('api.')->group(function () {
  ...
});

Then in RouteServiceProvider,

Route::prefix('api')
         ->middleware('api')
         ->namespace($this->namespace.'\Api')
         ->group(base_path('routes/api.php'));
Erin
  • 5,315
  • 2
  • 20
  • 36
  • 1
    The name can go in the `RouteServiceProvider` so the wrapper in `routes/api.php` isn't necessary. – None Mar 25 '21 at 20:26