英文:
Why Is Laravel Giving Me This Error, and How Do I Fix it? Argument #2 ($post) must be of type App\Models\Post, App\Models\User given
问题
我正在尝试使用一个 Gate 来检查当前认证用户是否与 "posts" 表的 user_id 列匹配。然而,在尝试在我的控制器中使用 Gate 时,它给我返回以下错误,我感到困惑。
App\Providers\AuthServiceProvider::App\Providers{closure}(): 第二个参数 ($post) 必须是类型 App\Models\Post,但传递的是类型 App.Models.User,在 [路径]\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php 的第 535 行调用。
我的控制器:
class updatePost extends Controller
{
    public function updatePost(Request $request, Post $post) {
        if (Gate::allows('updatePost', auth()->user(), $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;
});
英文:
I am trying to use a Gate to see if the currently authenticated user matches the user_id column of the "posts" table.
However, when attempting to use the Gate inside my controller, it is giving me the following error, and I am at a loss.
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
Thanks.
My Controller:
class updatePost extends Controller
{
  public function updatePost(Request $request, Post $post) {
    if (Gate::allows('updatePost', auth()->user(), $post)) {
      $post->title = $request->input('title');
      $post->body = $request->input('body');
      $post->save();
      return redirect()->route('readPost', ['id' => $post->id]);
    } else {
        echo 'ERROR';
    }
  }
}
My Gate:
Gate::define('updatePost', function (User $user, Post $post) {
          return $user->id === $post->user_id;
      });
答案1
得分: 1
The define callback always receives the logged in user as the first parameter, followed by the parameters given by allows().
尝试这样做
if (Gate::allows('updatePost', $post)) {
   // 你的代码
}
英文:
The define callback always receives the logged in user as first parameter followed but the parameters given by allows().
Try this
if (Gate::allows('updatePost', $post)) {
   // your code
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论