php 49 lines · 6 steps

Defining authorization gates in Laravel

A Laravel AuthServiceProvider registers Gate hooks and ability checks that control who can update, publish, and delete posts.

Explained by highlit
1<?php
2 
3namespace App\Providers;
4 
5use App\Models\Post;
6use App\Models\User;
7use Illuminate\Support\Facades\Gate;
8use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
9 
10class AuthServiceProvider extends ServiceProvider
11{
12 public function boot(): void
13 {
14 Gate::before(function (User $user, string $ability) {
15 if ($user->hasRole('super-admin')) {
16 return true;
17 }
18 
19 return null;
20 });
21 
22 Gate::define('post.update', function (User $user, Post $post) {
23 return $user->id === $post->author_id
24 && ! $post->isLocked();
25 });
26 
27 Gate::define('post.publish', function (User $user, Post $post) {
28 if ($user->id !== $post->author_id) {
29 return false;
30 }
31 
32 return $user->hasVerifiedEmail() && $post->isReady();
33 });
34 
35 Gate::define('post.delete', function (User $user, Post $post) {
36 return $user->id === $post->author_id
37 && $post->created_at->gt(now()->subDay());
38 });
39 
40 Gate::after(function (User $user, string $ability, ?bool $result) {
41 if ($result === false) {
42 activity('authorization')
43 ->causedBy($user)
44 ->withProperties(['ability' => $ability])
45 ->log('denied');
46 }
47 });
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Gate::before short-circuits every check, making it the natural home for global overrides like super-admin.
  2. 2Each gate closure returns a boolean built from ownership plus domain rules, keeping policy logic in one place.
  3. 3Gate::after lets you observe the outcome of every check for auditing without altering the decision.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Defining authorization gates in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code