1

I've Blog website where all user can post Blog.I have learned about Gates,Policy and Middleware .Please come to know that i am using Auth() Default Authentication Process in Laravel. I want to protect user (A) blog from other users.

Now I have many things to handle this.

Using Auth if(Auth()->user->id==$blog->user_id)

Using Gate if(Gate::Allow('blog_protection',$blog))

Using Policy if(Auth::user()->cant('blog_protection',$post))

Using Middleware $this->middleware('blog_access')

Please tell if i am wrong Meaning of that functions then what is best method to handle this request for more reusable . Many Thanks In Advance.

Martin Heralecký
  • 5,649
  • 3
  • 27
  • 65
Hashaam zahid
  • 315
  • 5
  • 21
  • 1
    Using middleware is very efficient I think, reusable and standard. I always use middleware but sometime I use Gate also. – Manzurul Hoque Rumi Feb 03 '19 at 04:51
  • 1
    There's a great answer here: https://stackoverflow.com/questions/35019292/laravel-difference-between-route-middleware-and-policy – kerrin Feb 03 '19 at 11:56

1 Answers1

2

I would consider writing a policy class for blog model resource. Multiple reasons :

  • You can list all access methods related to blog in one file to easy to track
  • You can do just $this->authorize('access_method_name', Blog::class) in controller
  • You can pass extra arguments to the method to filter it conditionally

  • If you have a method outside controller and you need to add filter(ideally the controller authorize() would filter it out) but still you can use

$user->can() or $user->cant().. 

which will internally use the same policy.

  • Also to mention you can use this in blade directives @can()...@ endcan @cannot...@endcannot

Middleware is something which would intervene in every request specified in the route group or all requests if its registered as global middleware group. If you want an access filter applicable globally in all routes then middleware is a better option. But for specific resource, I would prefer policies.

In short middleware for request filtering and handling whereas Policy for managing granular level access controls.

Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37