Laravel Advanced Auth & Jobs · 9 min read

Laravel Gates and Policies

Lesson 12 of 33 in the Laravel learning path.

How do I authorize an update so users only edit their own lesson?

Auth middleware proves that a request has a user. It does not decide which lesson that user may change. A policy is the class that answers those questions for a model. LessonPolicy::update receives the signed-in user and the lesson, and it returns true only when the user id matches the lesson owner.

Laravel discovers App\Policies\LessonPolicy for App\Models\Lesson. A controller calls $this->authorize('update', $lesson) before it writes. Guests never reach update, because that method type-hints User rather than a nullable user. A published lesson can still be viewed by anyone, while a draft stays with its owner.

Syntax & Parameters

Syntax
public function update(User $user, Lesson $lesson): bool
{
    return $user->id === (int) $lesson->user_id;
}

Example

app/Policies/LessonPolicy.php
<?php

namespace App\Policies;

use App\Models\Lesson;
use App\Models\User;

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

    public function view(?User $user, Lesson $lesson): bool
    {
        if ($lesson->published_at !== null) {
            return true;
        }

        return $user !== null && $user->id === (int) $lesson->user_id;
    }

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

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

    public function delete(User $user, Lesson $lesson): bool
    {
        return $this->update($user, $lesson);
    }
}

Expected Output

Ada owns lesson 1. Grace is signed in as a different user.

Ada   PUT /lessons/1   policy update returns true, controller saves
Grace PUT /lessons/1   policy update returns false, response 403
Guest PUT /lessons/1   auth middleware redirects to login
Guest GET /lessons/1   view returns true when published_at is set
Grace GET /lessons/4   view returns false when published_at is null and Grace is not the owner

Line-by-Line Walkthrough

  1. LessonPolicy sits in App\Policies. Laravel matches it to App\Models\Lesson by that name, so authorize can find it without a manual map.
  2. viewAny returns true for guests and members. The catalog route can call authorize('viewAny', Lesson::class) and stay public.
  3. view allows every published lesson. published_at null means a draft, and a draft is visible only when the user id equals user_id.
  4. The (int) cast keeps the comparison stable when the database value arrives as a string. Strict equality then compares two integers.
  5. create type-hints User, so a guest is denied before the method runs. A signed-in user with a real id may open the form.
  6. update is the ownership rule. The signed-in user can change a lesson only when that lesson stores their id.
  7. delete calls the same rule. The owner who may edit the lesson may also remove it.
  8. In the controller, $this->authorize('update', $lesson) runs this method and throws AuthorizationException on false, which Laravel renders as 403.
  9. A route can use middleware('can:update,lesson') when the route parameter is named lesson. The policy method is still the place that compares the ids.

Common Pitfalls & Security

A policy that is never called is the same as no policy. Middleware auth lets every signed-in student through the door, and a missing authorize call lets Grace save Ada's lesson. A before method that returns true skips every ability, including update.

  • Comparing ids with === and no cast fails when user_id is still a string. Cast one side, or cast user_id to integer on the model.
  • view that returns true for every draft publishes work the author has not released. Check published_at before you fall through to the owner test.
  • A hidden user_id field in the form is not the owner. Read the id from the authenticated user and from the stored lesson.
  • Gate::before that returns true for "staff" also allows those accounts to update every lesson. Return null from before when you want the policy methods to decide.
  • authorize belongs on update, delete, and any syllabus upload that changes the lesson. Checking it only on the edit form leaves the POST open.

Best Practices & Modern Standards

Keep one ability per method, and make update the ownership check for a lesson. Call authorize at the start of the controller action, or return $this->user()->can('update', $lesson) from a form request authorize method. The request then fails before validation messages and before any write.

Leave guests out of create, update, and delete by type-hinting User. Use ?User only on abilities a public page really has, such as view. When discovery is turned off in the application, register the class with Gate::policy(Lesson::class, LessonPolicy::class).

Real-World Use

Ada opens her Algebra I lesson and saves a new title. Grace, signed in as another instructor, posts the same update URL. The auth middleware lets Grace through because she has a session, and LessonPolicy::update returns false because the lesson user_id is Ada. Grace receives 403 and the row stays unchanged.

Frequently Asked Questions

Where do I call the policy?

Call $this->authorize('update', $lesson) in the controller action that saves the lesson. A form request can return $this->user()->can('update', $this->route('lesson')) from authorize.

Do I have to register LessonPolicy by hand?

Laravel discovers App\Policies\LessonPolicy for App\Models\Lesson. Add Gate::policy only when the class lives in another namespace or discovery is disabled.

What does a guest get from update?

The method requires a User, so an anonymous request is denied. On a web route the auth middleware usually redirects that guest to login before the policy runs.

Why cast user_id to int?

MySQL often returns an uncast integer column as a string. (int) $lesson->user_id lets === compare the same types and still reject a different owner.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…