Erin
Erin

Reputation: 5825

Get an API URL by route name in Laravel 5.5

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?

Upvotes: 4

Views: 10357

Answers (2)

ceejayoz
ceejayoz

Reputation: 180024

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

Upvotes: 3

Erin
Erin

Reputation: 5825

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'));

Upvotes: 3

Related Questions