在laravel中未经授权执行此操作

时间:2019-02-04 22:27:49

标签: php laravel laravel-5

我正在获取当我输入url localhost / website / post / 1 / edit时,此操作是未经授权的403。我想保护未经授权的用户编辑帖子。

在PostController中

public function edit($id)
{
$post=Post::findOrFail($id);
$this->authorize('check_access',$post);
return 'You are authorized';
}

在AuthServiceProvider.php

protected $policies = [
Post::class => 'PostPolicy::class',
];

在PostPolicy.php中

public function check_access($post)
{
return Auth::user()->id==$post->user_id;
}

在web.php中 Route::resource('post','PostController');

请告诉我我错了。我是Laravel的新人,完全感到沮丧。谢谢

1 个答案:

答案 0 :(得分:1)

你不应该让我的朋友完全沮丧。您应该阅读文档,以更好地了解要编写的代码。因此,只需遵循示例here,您应该一切都很好。因此,您可以将其作为第一个参数传递给方法,而不是从Auth保护中访问用户。

public function check_access(User $user, Post $post)
{
    return $user->id == $post->user_id;
}