【问题标题】:Setting the route parameter in the middleware in Laravel在 Laravel 的中间件中设置路由参数
【发布时间】:2019-06-16 03:42:16
【问题描述】:

我正在开发一个 Laravel 应用程序。我正在中间件中进行路由模型绑定。

我有这样的路线

Route::group([ 'prefix' => 'department/{department}', 'middleware' => [ 'auth.department' ] ], function () {
    Route::post('employee/create', 'EmployeeController@store')->name('employees.store');
});

这是我的 auth.department 中间件(AuthDepartment)

class AuthDepartment
{
    public function handle($request, Closure $next)
    {
        $department = Department::find($request->department);
        //do something with the department
        //I want to set the $department (Department model) in the place of {department} in the route.


        return $next($request);
    }
}

这是员工控制器

class EmployeeController extends Controller {
    public function store($department)
    {
    }
}

正如您在代码中看到的,我使用 $department 参数从路由中获取部门 ID。但是我不想将整数作为参数,而是想像这样绑定模型。

class EmployeeController extends Controller {
     public function store(Department $department)
     {
     }
}

使用我当前的代码,它不起作用。我尝试在中间件中设置路由参数,以匹配(绑定模型)动作中的值。

$request->route()->setParameter('department', $department)

但它只是不工作。如何使用中间件中的模型设置/替换路由参数,该模型可以绑定到控制器操作中的参数?可能吗?有什么更好的方法?

如果我用过

$request->route()->setParameter('department', $department)

要设置参数,我不能像这样在控制器的动作中设置类型。

store(Department $department)

不过没关系

 store(Department $department)

但我想要这个

store(Department $department)

【问题讨论】:

    标签: laravel model-binding laravel-routing laravel-middleware


    【解决方案1】:

    Laravel 已经内置了这个。它被称为 Route Model Binding。

    https://laravel.com/docs/5.7/routing#route-model-binding

    删除中间件,保持控制器不变。 Laravel 将自动使用请求中的 ID 来查找模型并为您提供它的实例。如果找不到模型,Laravel 会为你抛出 404 响应。

    【讨论】:

    • 但问题是你如何在中间件中获得模型值?它在中间件中没有绑定。
    • 为什么需要中间件中的模型值?
    • 因为我必须一直在路由中传递值才能访问我的应用程序的特定部分。我正在为此创建中间件。
    猜你喜欢
    • 2015-12-27
    • 2016-02-14
    • 2020-08-31
    • 2023-04-04
    • 2017-03-06
    • 1970-01-01
    • 2017-04-06
    • 2018-12-22
    • 2015-11-12
    相关资源
    最近更新 更多