php - 防止将路由前缀作为第一个参数传递给 Laravel 5 中的子路由

标签 php laravel laravel-5

如何防止将路由前缀作为第一个参数传递给所有子路由 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/

相关文章:

php - 我怎么知道在执行我的sql语句时出了什么问题

javascript - 如何使用 Angular JS 更新表中的值

php - PHP 如何四舍五入到小数点后两位

PHP: Slim Framework/Eloquent ORM 批量分配错误

unit-testing - 单元测试 Laravel 中间件

laravel - 如何在laravel中选择最小值和最大值

php - 使用 PHP Form 将数据更新到 MySql 数据库

php - Laravel 覆盖 EloquentUserProvider 以更改 validateCredentials() 中的密码字段名称

php - Laravel Eloquent 收集配对项目

javascript - CSS 未加载到动态生成的 Laravel View 中