在 laravel 中获取此操作是未经授权的

Posted

技术标签:

【中文标题】在 laravel 中获取此操作是未经授权的【英文标题】:Getting this action is unauthorized in laravel 【发布时间】:2019-02-04 22:27:49 【问题描述】:

当我输入 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】:

我的朋友,你不应该完全沮丧。您应该阅读文档以更好地理解您尝试编写的代码。因此,只需按照示例 here 进行操作即可。因此,您可以将其作为第一个参数传递给方法,而不是从 Auth 守卫访问用户。

public function check_access(User $user, Post $post)

    return $user->id == $post->user_id;

【讨论】:

以上是关于在 laravel 中获取此操作是未经授权的的主要内容,如果未能解决你的问题,请参考以下文章