Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 67 ยท Authentication and Authorization

Gates and Policies

Learn Laravel authorization: Gate::define, policies made with make:policy, authorize in controllers, @can in Blade, policy responses, guests and before hooks.

Authentication tells you who the user is. Authorization decides what that user may do: edit this post, delete that comment, see the billing page. The worst place to answer that question is scattered if ($post->user_id === auth()->id()) checks copied across controllers, Blade files and API endpoints. They drift apart, one gets forgotten, and a user edits someone else's data.

Laravel centralizes the rules in two tools. A gate is a closure for a one-off ability ("can this user view the admin dashboard?"). A policy is a class that groups all the rules for one model ("who can view, update or delete a Post?"). Then everywhere else you ask the same question, can, authorize or @can, and the rule lives in exactly one place. Make sure you are comfortable with Authentication Overview and Starter Kits first, since every rule starts from the authenticated user.

Gates

A gate is defined once, typically in the boot method of App\Providers\AppServiceProvider. The first parameter is always the current user; any further parameters are what you pass when you ask.

PHP
use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Facades\Gate;

public function boot(): void
{
    Gate::define('view-admin-dashboard', function (User $user): bool {
        return $user->is_admin;
    });

    Gate::define('update-post', function (User $user, Post $post): bool {
        return $user->id === $post->user_id;
    });
}

You then ask the question anywhere:

PHP
if (Gate::allows('update-post', $post)) {
    // the current user may update it
}

if (Gate::denies('update-post', $post)) {
    abort(403);
}

Gate::authorize('update-post', $post);   // throws AuthorizationException (a 403 response) if denied

Gate::authorize() is the one you will use most in controllers because it needs no if: either the code continues or a 403 response is produced. Other helpers: Gate::any([...], $arg) (at least one ability passes), Gate::none([...], $arg), Gate::check() (alias of allows for several abilities), and Gate::forUser($otherUser)->allows(...) to test somebody who isn't the current user, for example in an admin tool or a queued job.

Gates are great for abilities that are not tied to a model. Once you have a growing set of rules around the same model, switch to policies.

Policies

A policy is a plain class with one method per action. Generate it with Artisan; --model fills the standard methods for you:

Terminal
php artisan make:policy PostPolicy --model=Post
PHP
namespace App\Policies;

use App\Models\Post;
use App\Models\User;

class PostPolicy
{
    public function viewAny(User $user): bool
    {
        return true;
    }

    public function view(?User $user, Post $post): bool
    {
        return $post->published_at !== null || $user?->id === $post->user_id;
    }

    public function create(User $user): bool
    {
        return $user->hasVerifiedEmail();
    }

    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post): bool
    {
        return $user->id === $post->user_id || $user->is_admin;
    }
}

The standard method names mirror the resource actions of Controllers: viewAny, view, create, update, delete, restore and forceDelete. Two details matter:

  • Guests. A gate or policy method whose user parameter is non-nullable is never called for a guest; Laravel denies automatically. To let guests through, as view does above, type the user as ?User (or give it a default of null).
  • Registration is automatic. If a model is App\Models\Post, Laravel looks for App\Policies\PostPolicy by naming convention. You rarely register anything by hand.

Using policies

In a controller, Gate::authorize() takes the action and the model. Because the model is a Post, Laravel finds PostPolicy and calls update:

PHP
public function update(Request $request, Post $post): RedirectResponse
{
    Gate::authorize('update', $post);

    $post->update($request->validated());

    return to_route('posts.show', $post);
}

public function store(Request $request): RedirectResponse
{
    Gate::authorize('create', Post::class);   // no instance yet: pass the class
    // ...
}

You can also check from the user, from middleware and from Blade:

PHP
$request->user()->can('update', $post);
$request->user()->cannot('update', $post);
PHP
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('can:update,post');   // 'post' is the route parameter, resolved by model binding
BLADE
@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan

@cannot('delete', $post)
    <p>You can't delete this post.</p>
@endcannot

@canany(['update', 'delete'], $post)
    <div class="toolbar"> ... </div>
@endcanany

Model binding in the route (see Route Groups and Model Binding) is what lets the can:update,post middleware hand a real model to the policy. Notice that you hide the Edit link with @can, but you must also authorize in the controller: hiding a button is not security, only manners.

flowchart TD
    A["Gate::authorize('update', $post)"] --> B{"Before callbacks<br/>return true or false?"}
    B -->|"yes"| R["Use that result"]
    B -->|"null"| C["Find policy for model<br/>(PostPolicy)"]
    C --> D{"Policy before()<br/>returns a result?"}
    D -->|"yes"| R
    D -->|"null"| E["Call update($user, $post)"]
    E --> R
    R -->|"allowed"| OK["Controller continues"]
    R -->|"denied"| F["AuthorizationException<br/>403 response"]

Laravel runs global before callbacks, then the policy's own before method, then the action method.

A gate and policy engine you can run

The framework resolves policies by convention and runs before-hooks in a fixed order. The stand-in below does the same with a few dozen lines: gates registered by name, policies found by model class, a before hook, and an authorize method that throws. Laravel's real implementation also handles guests, responses and after callbacks; the logic here is the same shape.

PHP A mini Gate with policies and a before hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Ben may read Ana's published post but not her draft, a guest may view published content because view takes ?User, and the admin passes everything through the before hook except the dashboard check, where the hook defers to the gate. Unknown abilities are denied by default, a safe habit that Laravel shares.

Responses with messages

A policy method normally returns a boolean. When you want to explain why or change the status code, return a Response:

PHP
use Illuminate\Auth\Access\Response;

public function update(User $user, Post $post): Response
{
    if ($user->id === $post->user_id) {
        return Response::allow();
    }

    return Response::deny('You do not own this post.');
}

Gate::inspect('update', $post) returns the response object so you can read $response->allowed() and $response->message(). For resources whose very existence you want to hide from unauthorized users, Response::denyAsNotFound() makes the denial a 404; Response::denyWithStatus(418) picks another code. Hiding existence is an old security habit: a 403 on /invoices/123 confirms that invoice 123 exists.

Before hooks and super admins

A before callback runs ahead of every check. Returning true allows everything, false denies everything, and null lets normal checks continue. This is the classic place for a super-admin rule:

PHP
Gate::before(function (User $user, string $ability) {
    if ($user->is_admin) {
        return true;
    }
});

A policy can also declare its own before($user, $ability) method that applies to that policy only, which is better when only one model has an override. Be careful with global bypasses: they apply to every ability, including ones added next year. There is a matching Gate::after() for logging or last-word decisions.

Return null, not false, when you don't want to decide, otherwise a non-admin would be denied everything. The stand-in's hook returned null for non-admins for exactly this reason.

Policy results as data

Policies shine because they are plain objects: testable without a browser. You can instantiate PostPolicy in a unit test and call update($user, $post) directly, or use $this->actingAs($user)->put(...)->assertForbidden() in a feature test; see HTTP and Database Tests. The same policy also feeds API responses and Blade, so there is one source of truth.

The next TryIt runs a policy over a table of users, roles and actions. Printing the result as a matrix is a good habit in real projects too: the table is documentation, and diff-friendly when rules change.

PHP A policy decision matrix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the table by column: only the author can update a non-archived article, deleting is restricted to drafts, and the admin row is all yes because before returned true. If a rule changes, such as letting editors update published articles, you edit one method and the whole application follows.

Authorize in the controller (or with can: middleware) for every route that reads or changes protected data, and use @can only to hide buttons. A hidden button can still be requested by hand.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When should you prefer a policy over a gate?

    Policies group all the rules for a model in one class and are discovered by naming convention. Gates suit one-off abilities.
  2. 2. What happens when Gate::authorize('update', $post) is denied?

    authorize() is the throwing version of allows(): no if statement is needed, because denial stops the request with a 403.
  3. 3. How can a policy method allow guests to pass?

    Laravel denies guests automatically for non-nullable user parameters. A nullable user type means the method accepts a guest.
  4. 4. What should a Gate::before callback return when the user is not an admin?

    null means no decision, so normal gate and policy checks continue. Returning false would deny everything to non-admins.
  5. 5. Why is wrapping a button in @can not enough to protect an action?

    Hiding UI is cosmetic. The server must check the permission on every request that changes or reads protected data.

Summary

  • Gates are closures for one-off abilities (Gate::define); policies are classes with one method per action for a model, created with php artisan make:policy PostPolicy --model=Post.
  • Policies are discovered by convention (App\Models\Post finds App\Policies\PostPolicy).
  • Ask with Gate::allows, Gate::denies, Gate::authorize (throws a 403), $user->can(), the can: middleware and @can / @cannot / @canany in Blade.
  • Non-nullable user parameters deny guests automatically; use ?User to allow them.
  • Return a Response (deny('message'), denyAsNotFound()) for custom messages or status codes; Gate::inspect reads it.
  • Gate::before or a policy before method implements super-admin rules; return null to continue normal checks.
  • Hiding a button is UI; always authorize on the server too.

Next: Roles and Permissions Patterns