1

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

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

It's the first time I use middleware. I created the SetStoreIdFromRequest middleware, registered it, assigned it to the route. and everything went well. Thanks!
2

In my Laravel 9 project I am doing it like this:

web.php

Route::get('/world', [NewsController::class, 'section'])->defaults('category', "world");

NewsController.php

public function section($category){}

Comments

-3

Laravel works exactly in the way you described.

You can access storeId in your controller method

class DashboardController extends Controller {
    public function index($storeId) {
        dd($storeId);
    }
}

http://localhost/admin/20 will print "20"

4 Comments

I am not having problems with accessing route parameters. I want the route parameter to take default value. but the default value will not be provided as static value in the routing settings. however it will be provided from the request url.
you should set default in controller method public function index($storeId = 10)
This sentence is not so clear to me I want storeId to be set automatically from the request URL if provided.
This answer is basic routing and not how to set a default - if you explained how localhost/admin to that same url would print "20" if 20 was the default value.. that would be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.