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

huangapple go评论63阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2023年2月10日 02:45:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定