如何防止将路由前缀作为第一个参数传递给所有子路由 Controller 函数?它弄乱了我的子路由的 $id 参数!
Route::prefix('{locale?}')->middleware(['locale.default', 'locale'])->group(function() {
Route::get('/car/{id}', [
'uses' => 'CarController@getCar',
'as' => 'car',
'middleware' => 'auth'
])->where(['id' => '[0-9]+']);
});
在 CarController 的 getCar() 函数中,id 参数获取语言环境(en、fr、it)而不是传递的汽车的 id。
public function getCar($id)
{
$car = Car::where('id', $id)->firstOrFail();
}
要解决这个问题,我必须这样做:
public function getCar($locale, $id)
{
$car = Car::where('id', $id)->firstOrFail();
}
有没有办法简单地阻止将 $locale 传递给子路由的 Controller 函数,这样我就不必将 $locale 作为第一个参数添加到每个函数?
如果我将 getCar() 参数从 $id 更改为 Request 类型的 $request,我可以这样做并且它有效。这是一个好的解决方案吗?
public function getCar(Request $request)
{
$car = Car::where('id', $request->id)->firstOrFail();
}
Laravel 5.6 文档似乎说这是可以做到的: https://laravel.com/docs/5.6/requests
Accessing The Request Via Route Closures
You may also type-hint the Illuminate\Http\Request class on a route Closure. The service container will automatically inject the incoming request into the Closure when it is executed:
use Illuminate\Http\Request;
Route::get('/', function (Request $request) { //... });
有人可以确认一下吗?谢谢!
最佳答案
使用中间件,您只需将此行添加到处理程序:
$request->route()->forgetParameter('prefix');
关于php - 防止将路由前缀作为第一个参数传递给 Laravel 5 中的子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100429/