gpt4 book ai didi

php - 路由 : Too few arguments to function 1 passed 2 expected 上的 Laravel 策略

转载 作者:行者123 更新时间:2023-12-03 23:50:48 25 4
gpt4 key购买 nike

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

web.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 Too few arguments to function App\Policies\ThoughtRecordPolicy::isOwner(), 1 passed in /Applications/MAMP/htdocs/thought-records/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 706 and exactly 2 expected



编辑:

我将路线更改为:
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 documentation :

In this example, we're passing the can middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method. In this case, since we are using implicit model binding, a Post model will be passed to the policy method.


所以你基本上需要使用隐式模型绑定(bind)并将路由参数作为第二个参数传入。
希望能帮助到你!

关于php - 路由 : Too few arguments to function 1 passed 2 expected 上的 Laravel 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58151996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com