Search code examples
laravellaravel-5routesrouteparams

How to set a route parameter default value from request url in laravel


I have this routing settings:

Route::prefix('admin/{storeId}')->group(function ($storeId) {
  Route::get('/', 'DashboardController@index');
  Route::get('/products', 'ProductsController@index');
  Route::get('/orders', 'OrdersController@index');
});

so if I am generating a url using the 'action' helper, then I don't have to provide the storeId explictly.

{{ action('DashboardController@index') }}

I want storeId to be set automatically from the request URL if provided.

maybe something like this.

Route::prefix('admin/{storeId}')->group(function ($storeId) {
  Route::get('/', 'DashboardController@index');
  Route::get('/products', 'ProductsController@index');
  Route::get('/orders', 'OrdersController@index');
})->defaults('storeId', $request->storeId);

Solution

  • The docs mention default parameter though in regards to the route helper (should work with all the url generating helpers):

    "So, you may use the URL::defaults method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a route middleware so that you have access to the current request"

    "Once the default value for the ... parameter has been set, you are no longer required to pass its value when generating URLs via the route helper."

    Laravel 5.6 Docs - Url Generation - Default Values