如何根据 laravel 中的请求 url 设置路由参数默认值

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

我有这样的路由设置:

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

因此,如果我使用 'action' 帮助程序生成 url,那么我不必明确提供商店 ID。

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

我希望根据请求 URL 自动设置 storeId(如果提供的话)。

可能是这样的。

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

Laravel 完全按照您描述的方式工作。

您可以在控制器方法中访问 storeId

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

http://localhost/admin/20 将打印“20”

虽然关于 route 助手(应该与所有 url 生成助手一起工作),但文档提到了默认参数:

"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