Laravel报错:Argument #2必须为App\Models\Post类型,传入User如何解决?
Laravel Gate 验证参数错误修复
错误信息
App\Providers\AuthServiceProvider::App\Providers{closure}(): Argument #2 ($post) must be of type App\Models\Post, App\Models\User given, called in [path]\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 535
问题原因
你的Gate定义中第一个参数是当前认证用户(User $user),Laravel会自动注入当前登录用户作为Gate闭包的第一个参数,不需要手动传递。但你在控制器调用Gate::allows()时,额外传入了auth()->user(),导致参数顺序混乱:原本应该传入$post的第二个参数位置,被auth()->user()占据,触发类型校验失败。
修复步骤
直接去掉Gate::allows()中的auth()->user()参数,仅传递$post即可。
修复后的控制器代码
class updatePost extends Controller { public function updatePost(Request $request, Post $post) { if (Gate::allows('updatePost', $post)) { $post->title = $request->input('title'); $post->body = $request->input('body'); $post->save(); return redirect()->route('readPost', ['id' => $post->id]); } else { echo 'ERROR'; } } }
原Gate定义无需修改
Gate::define('updatePost', function (User $user, Post $post) { return $user->id === $post->user_id; });
内容的提问来源于stack exchange,提问作者MothManDeluxe
相关产品推荐
相关产品推荐

