Search code examples
phplaravellaravel-routinglaravel-5.5

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?


Solution

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