Gates vs. policies
Laravel provides two primary tools for authorization: gates and policies.- Gates are closures. Use them for simple checks that aren’t tied to a specific model, such as “can this user access the admin dashboard?”
- Policies are classes. Use them to group authorization logic around a particular model or resource.
Gates
Gate authorization flow
Defining gates
Define gates inside theboot method of App\Providers\AppServiceProvider using the Gate facade. Gates receive the authenticated user as their first argument, plus any additional arguments you pass:
Checking gates
CallGate::allows or Gate::denies in a controller to guard an action:
abort, use Gate::authorize:
Gate responses
Return a detailedResponse from a gate instead of a boolean to include an error message:
Gate::inspect:
Policies
Policy authorization flow
Generating policies
Create a policy class with Artisan:app/Policies. The --model flag pre-fills CRUD method stubs.
Auto-discovery
Laravel automatically discovers policies by convention. A model atApp\Models\Post is paired with a policy at App\Policies\PostPolicy. To register a policy explicitly, call Gate::policy inside AppServiceProvider::boot:
Writing policy methods
Each method receives the authenticated user and, usually, the model instance. Return a boolean (or aResponse) to allow or deny:
Policy responses
Return aResponse to attach a custom message to a denial:
Actions without a model instance
Some policy methods, likecreate, don’t operate on an existing model. Define them with only the user argument:
Guest users
By default, gates and policies returnfalse for unauthenticated users. To allow guests through to the policy, mark the user argument as nullable:
Policy filters
To give a user unrestricted access before any other checks run, define abefore method on the policy:
null from before delegates to the specific policy method.
Before callback execution order
Authorizing actions using policies
Via the user model
TheUser model exposes can and cannot methods. Pass the ability and the model instance:
create), pass the policy class instead:
Via the Gate facade
Via middleware
Use thecan middleware to guard routes:
Via Blade templates
Use@can, @cannot, and @canany directives in Blade views:
A complete example
1
Generate the policy
2
Define authorization rules
3
Protect the controller
4
Protect views