首页 > 解决方案 > Laravel 路由政策:函数 1 的参数太少,预期通过 2

问题描述

我制定了一项政策来保护我的模型。我要做的是阻止任何人编辑不存在的思想记录。

网页.php

Auth::routes();

Route::prefix('/')->middleware(['auth','can:viewAny,App\ThoughtRecord'])->group(function() {

    Route::get('/record/{id}/edit', 'ThoughtRecordController@edit')->middleware('can:isOwner,App\ThoughtRecord');

    Route::patch('/record/{thoughtRecord}','ThoughtRecordController@update')->middleware('can:isOwner,App\ThoughtRecord');

});

ThoughtRecordPolicy.php

public function isOwner(User $user, ThoughtRecord $thoughtRecord)
{
    return $user->id == $thoughtRecord->user_id;

}

->middleware(['auth','can:viewAny,App\ThoughtRecord'])作品非常好。其他路由上的中间件没有->middleware('can:isOwner,App\ThoughtRecord'),并产生此错误:

错误

Symfony\Component\Debug\Exception\FatalThrowableError 函数参数太少 App\Policies\ThoughtRecordPolicy::isOwner(), 1 传入 /Applications/MAMP/htdocs/thought-records/vendor/laravel/framework/src/Illuminate/Auth /Access/Gate.php 在第 706 行,预计正好 2

编辑:

我将路线更改为:

Route::get('/record/{thoughtRecord}/edit', 'ThoughtRecordController@edit')->middleware('can:isOwner,thoughtRecord');

现在我得到一个 403,条件是我非常肯定是真的。

标签: phplaravellaravel-6policies

解决方案


您错误地将第二个参数传递给isOwner策略的方法。

以下应该有效:

Route::get('/record/{thoughtRecord}/edit', 'ThoughtRecordController@edit')
   ->middleware('can:isOwner,thoughtRecord');

根据laravel 文档

在这个例子中,我们向 can 中间件传递了两个参数。第一个是我们希望授权的操作的名称,第二个是我们希望传递给策略方法的路由参数。在这种情况下,由于我们使用的是隐式模型绑定,因此 Post 模型将被传递给策略方法。

所以你基本上需要使用隐式模型绑定并将路由参数作为第二个参数传入。

希望能帮助到你!


推荐阅读