php - 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,条件是我非常肯定是真的。
解决方案
您错误地将第二个参数传递给isOwner
策略的方法。
以下应该有效:
Route::get('/record/{thoughtRecord}/edit', 'ThoughtRecordController@edit')
->middleware('can:isOwner,thoughtRecord');
根据laravel 文档:
在这个例子中,我们向 can 中间件传递了两个参数。第一个是我们希望授权的操作的名称,第二个是我们希望传递给策略方法的路由参数。在这种情况下,由于我们使用的是隐式模型绑定,因此 Post 模型将被传递给策略方法。
所以你基本上需要使用隐式模型绑定并将路由参数作为第二个参数传入。
希望能帮助到你!
推荐阅读
- arrays - 如何从包含值的 JSON 对象中的数组中删除元素
- php - HowTo:在 PHP 中将两个数组中的值与相同的键合并
- python - md5sum 输出和 Python hashlib 输出有什么区别?
- ios - IOS 应用程序因“bug_type”而崩溃:“179”
- mysql - 尝试将 txt 文件插入 MySql 时出现 MySql 错误 1054
- reactjs - Flow 给出错误“无法将 [value] 分配给 this.[property],因为 [class] 中缺少属性 [property]”
- c# - 使用 VSCode 和 .NET Core 设置 xUnit 时出现问题,如何正确设置?
- three.js - 三个 Js BufferGeometry Loader 给了我一个“Uncaught TypeError: Cannot read property 'index' of undefined”为什么?
- sockets - TCP 套接字可能会中断以使其仍在接收但不能再发送?
- javascript - 如何使用相同的 script.js 文件使用多个 Id 调用不同的 CSS 类