Gates, Policies, Guards and Middleware. When you first use them, they all seem very similar. But in fact each have a use for a specific area of authorisation and settings rules throughout your website.
If you’re new or confused with Laravel’s authorisation/authentication with how various authorisation features work in Laravel, here is my attempt at explaining what each of the main features do and what purpose they have. On the surface it’s possible that each feature overlaps the other, their uses are quite broad but each have a specific purpose despite their subtleties. I’ll go through over Gates, Policies, Guards and Middleware.
Gates and Policies
The purpose of gates and policies is based around the idea of permissions; whether a user has permission to perform an action or not. A typical action for a blog would be whether a freelance writer would be allowed to write, read, update, create a blog post. Or perhaps the web app only allows an assistant editor to update but not create a blog post.
Gates and policies offer the same result with a different approach. In the Laravel docs, the author invites you to think of gates and policies like that of routes and controllers
“Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource. We'll explore gates first and then examine policies.” Laravel Authorization Docs
Gates offer an inline solution while policies do with a largely organised approach. While it is preferred to keep our code as neat as possible, using a gate with a specific ruleset for a user is where gates shine. While if we want to apply a rule for a general model or class, it’s best to stick with a policy.
Laravel Gate Video
Laravel Policy Video