Has*_*hid 4 php laravel laravel-4 laravel-5
我正在使用 laravel 基本策略系统来保护未经授权的用户免受更新发布的影响。例如,用户的 ID 为 1,帖子表中的User_id也为 1。
现在$this->authorize('update',$post);我只能传递一个变量$post来进行身份验证。在can方法中我还可以使用$user变量$user->can('update',$post)进行授权。
这是代码:
在 PostPolicy.php 中:
public function update(User $user, Post $post)
{
    return $user->id === $post->user_id;
}
在 AuthServiceProvider.php 中:
protected $policies = [
    Post::class => PostPolicy::class
]
在控制器授权方式中:
public function update(Request $request, $id)
{
    $post=Post::find(1);
    $user=User::find(1); 
    $this->authorize('update',$post);
    return 'Hello Everything Access For You ';
}
在控制器中使用 can 方法:
public function update(Request $request, $id)
{
    $post=Post::find(1);
    $user=User::find(1); 
    if($user->can('update',$post)){
        return 'Your are allowed';
    }
    else
    {
        return 'Your are Not allowed'; 
    }
}
我适合这两个功能吗?有什么区别吗。我必须使用哪种方法。提前致谢。
如果您使用authorize()或 中的任何一个can(),目的是验证用户是否有权执行某些任务。
但 :
在这种情况下authorize(),如果失败(从策略方法返回 false),授权方法将抛出 Illuminate\Auth\Access\AuthorizationException,默认的 Laravel 异常处理程序会将其转换为带有 403 的 HTTP 响应
对于can(),它只是检查用户是否被授权的基本方法,然后您需要自己处理其余的事情。比如如果未经授权该怎么办。
考虑到以上因素,我想说$this->authorize('update',$post);在控制器中使用更容易。
在文档中查看更多相同内容
你也可以这样做:
$request->user()->can()如果您想检查当前请求用户的授权。
更新 :
authorize()旨在授权当前登录的用户,laravel 自动将当前用户传递给策略。
can而您可以在任何用户实例上使用。
$request->user()->can()如果您想检查当前请求用户的授权。$user = $user::find($id); $user->can(...)如果是其他用户