Laravel: Difference Between Route Middleware and Policy

前端 未结 3 1483
天命终不由人
天命终不由人 2021-01-30 11:21

Developing an app with laravel I realised that what can be done with Policy can exactly be done with Middleware. Say I want to prevent a user from upda

3条回答
  •  旧时难觅i
    2021-01-30 12:05

    I have asked myself the same question. In practice, I predominantly use middleware. My most common usage is when authorisation is only allowed for a specific user, for instance:

    public function update(User $user, user $model)
    {
        return $user->id === $model->id;
    }
    

    Though, even in the instance above, Yes, one could do without it and write their own logic in the controller to do the same thing.

    I also like the before method, which I use to allow the administrator full-privileges for a model, for example:

    public function before($user, $ability)
    {
        if ($user->admin === 1) {
            return true;
        }
    }
    

    The main reason, though, why I have started to use Policies on some Laravel projects is because of what you can do with blade. If you find yourself setting permissions numerous times for the same user authorisation in your blade files, for example, to show an edit button, then Policies may become very useful because you can do the following with them (and more):

    @can('update', $post)
    
    @endcan
    
    @cannot('create', App\Models\Post::class)
    
    You are not allowed to create a post
    @endcannot

    I sometimes find these Policy-referencing blade methods to be super useful, when wanting to group authorisation in one place.

提交回复
热议问题