Last updated: 19 November 2026. Every behavior below was run on Laravel 13.40 and PHP 8.3 with MySQL. SeeHow this was checked.
Route model binding makes it very easy to write this:
Route::get('/documents/{document}', fn (Document $document) => $document); It works, it is short, and it hands any visitor any document whose id they can guess. Authentication tells you who is asking. It does not tell you whether they may see this record. That second check is authorization, and Laravel gives you two tools for it: gates and policies. This article shows how to use them so that no record is reachable without a check, and which parts of the framework's behavior will surprise you.
See the problem first
I built a small app with users, documents and comments. Alice and Bob each own a private document. The route above has no authorization. Results:
- Alice requested Bob's private document: 200, with his title.
- A guest (not logged in) requested it: 200 too, because that route had no
authmiddleware either.
This class of bug is usually called IDOR (insecure direct object reference): the id in the URL is the only thing standing between users and each other's data. A policy closes it.
Gates and policies: which to use
- Gate: a closure registered with
Gate::define(). Good for actions that are not about one record, such as "can this user open the admin settings". - Policy: a class with one method per action on one model (
view,update,delete). Use it whenever the question is "can this user do X to this record".
// A gate Gate::define('manage-settings', fn (User $user) => $user->is_admin); I tested that gate with two users: it returned false for a normal user and true for an admin.
Write the policy
php artisan make:policy DocumentPolicy --model=Document // app/Policies/DocumentPolicy.php namespace App\Policies; use App\Models\Document; use App\Models\User; class DocumentPolicy { public function viewAny(User $user): bool { return true; // may open the list (see "Lists" below) } public function view(User $user, Document $document): bool { return $document->published || $user->id === $document->user_id; } public function create(User $user): bool { return true; } public function update(User $user, Document $document): bool { return $user->id === $document->user_id; } public function delete(User $user, Document $document): bool { return $user->id === $document->user_id; } } I did not register this policy anywhere, and it still applied: Laravel's auto-discovery matched App\Models\Document to App\Policies\DocumentPolicy. If your policy lives somewhere else, register it with Gate::policy(Document::class, DocumentPolicy::class).
Use it in the controller
The Laravel 13.x application skeleton has an empty base Controller class, so there is no $this->authorize() helper in a new project. The current docs use the Gate facade:
use Illuminate\Support\Facades\Gate; public function show(Document $document) { Gate::authorize('view', $document); return $document; } public function destroy(Document $document) { Gate::authorize('delete', $document); $document->delete(); return response()->noContent(); } Gate::authorize() throws an AuthorizationException, which becomes a 403. Results with the policy in place:
| Request | Result |
|---|---|
| Alice views her own document | 200 |
| Alice views Bob's private document | 403, {"message":"This action is unauthorized."} |
| Alice views Bob's published document | 200 |
| Alice deletes Bob's document | 403, and the row still existed afterwards |
Not logged in, behind auth middleware | 401 |
Other places you can enforce the same policy, all using the same ability names:
- Route middleware:
Route::get('/documents/{document}', ...)->can('update', 'document'). Alice got 403 on Bob's document and 200 on her own. - Form requests:
return $this->user()->can('update', $this->route('document'));inauthorize(). Alice updating Bob's document got 403 and his title was unchanged. Note the order: a request from the wrong user with an invalid body got 403, while the owner with the same invalid body got 422, so authorization runs before validation. - Blade and code:
$user->can('update', $document),@can. I usedcan()in code; I did not test Blade directives.
Lists: the policy does not filter rows
This is an easy mistake to make. viewAny answers "may this user open the list at all". It does not remove other people's rows. I wrote an index that authorized viewAny and then returned Document::all(). Alice got all three documents, including Bob's private one, with a 200.
Scope the query to what the user may see:
public function index(Request $request) { Gate::authorize('viewAny', Document::class); return $request->user()->documents()->get(); // only her rows } With that, Alice's list contained only her document. If visibility rules are more complex (own documents plus published ones, say), put them in a query scope and reuse it, and keep the policy's view in agreement with it. Two places for the rule means two places to get it wrong.
Defaults that protect you, and ones that hide bugs
- Undefined abilities are denied.
Gate::allows('nope')returned false andGate::authorize('nope')threwAuthorizationException: This action is unauthorized.Safe, but a typo is also silent:$user->can('updat', $document)returned false with no error. If a legitimate user is suddenly forbidden, check the ability name first. - Guests are denied by default. A route with no
authmiddleware and a policy method typedview(User $user, ...)gave a guest 403, even for a published document. To let guests through, make the user parameter nullable:viewAsGuest(?User $user, Document $document). A guest got 200 on a published document and 403 on a private one that way. - Policy runs after the model is found. A missing id returned 404 and Bob's private document returned 403 to Alice. A person can tell the two apart and learn that the record exists. If that matters, return
Response::denyAsNotFound()from the policy method and the answer becomes 404 in both cases; I tested that and got404 {"message":"Not Found"}.
use Illuminate\Auth\Access\Response; public function viewPrivate(User $user, Document $document): Response { return $user->id === $document->user_id ? Response::allow() : Response::denyAsNotFound(); } You can also attach a message: Response::deny('You do not own this document.'). With Gate::authorize() the message came back in the 403 body, and Gate::inspect() returned it without throwing (allowed() false, message() set, code() null).
The before hook: handle with care
A before callback runs ahead of the policy methods, usually to let administrators do anything:
Gate::before(fn (User $user, string $ability) => $user->is_admin ? true : null); The return value matters:
-
truegrants the action and skips the policy. The admin could update Alice's document. -
nullmeans "no opinion, carry on to the policy". With the callback above, Alice could still update her own document and not Bob's. -
falsedenies it and skips the policy. When I changed the callback to$user->is_admin ? true : false, Alice could no longer update her own document.
Return null, not false, for "not an admin". Per the Laravel docs, inline checks such as Gate::allowIf() do not run before or after hooks.
Nested routes: scope the bindings
Policies check the models you pass them. They cannot know that the id in the URL was meant to belong to a different parent. I defined /documents/{document}/comments/{comment} and requested Alice's document with Bob's comment id:
- Without scoped bindings: 200, and the response contained Bob's comment text.
- With
Route::scopeBindings()on the same URL: 404. - With the matching parent (Bob's document and Bob's comment): 200.
Route::scopeBindings()->get( '/documents/{document}/comments/{comment}', [CommentController::class, 'show'], ); Scoped bindings make Laravel look the child up through the parent's relationship. Then authorize the parent (or the comment) as usual.
Creating records
The create ability has no model yet, so pass the class: Gate::authorize('create', Document::class). Set the owner from the authenticated user, never from the request body. In my store action the new document got user_id from $request->user()->documents()->create(...), and its owner was Alice. If the new record belongs to something the user can access, such as a team, authorize against that parent, and the docs show passing an extra argument: Gate::authorize('update', [$post, $request->category]).
Test it
Write at least one "forbidden" test per endpoint that takes an id. These are the assertions I used:
it('does not let a user read another user\'s private document', function () { $alice = User::factory()->create(); $bobDoc = Document::factory()->for(User::factory())->create(); $this->actingAs($alice)->getJson("/documents/{$bobDoc->id}")->assertForbidden(); }); In my own tests I created the records by hand instead of factories, and I checked status codes and response bodies rather than assertForbidden() itself, so treat the snippet above as the standard idiom rather than something I ran verbatim. One practical trap I hit: in a single test, actingAs() stays in effect for later requests, so a "guest" request made after it is not a guest request. Put guest checks in their own test.
Where policies do not run automatically
- Queued jobs, console commands and scheduled tasks have no logged-in user. If a job acts for a user, pass the user id and authorize explicitly, for example with
Gate::forUser($user)->allows(...), which I used in my tests. - Raw queries,
DB::table()and aggregate endpoints skip model policies entirely. - Nothing authorizes a route you forgot to protect. Search your routes for any that take a model binding and have no authorization call or
canmiddleware.
Checklist
- Every route with a model binding has a policy check, a
canmiddleware, or a form requestauthorize(). - Lists are scoped in the query, not only checked with
viewAny. - Nested routes use
scopeBindings(). - Admin bypass returns
trueornull, neverfalse. - Sensitive resources use
denyAsNotFound()so existence is not revealed. - Guest access is deliberate: a nullable
?Userparameter. - Owners are set from the authenticated user.
- Each endpoint has a forbidden-path test.
Related Dev Talk articles
- Laravel Security Checklist for Production
- REST API Best Practices
- Laravel SQL Injection Prevention
- Laravel File Upload Security
Frequently asked questions
What is the difference between a gate and a policy?
A gate is a closure for a general action. A policy is a class that groups the actions for one model. Use policies for record-level checks.
Why does $this->authorize() not exist in my controller?
The Laravel 13.x skeleton's base controller is empty. Use Gate::authorize() as the docs do, or add the AuthorizesRequests trait yourself.
Does viewAny filter the list?
No. It only decides whether the user may see the list. Filter the query.
Should I return 403 or 404 for someone else's record?
403 is accurate; 404 hides that the record exists. Use Response::denyAsNotFound() where existence is sensitive.
Why is a guest denied on a public document?
Because the policy method requires a User. Type the parameter as ?User to allow guests.
update log
- 19 November 2026: first version.
- To recheck: policy auto-discovery rules and the base controller in new skeleton versions.
Sources
- Laravel documentation: Authorization
- Laravel documentation: Routing, implicit model binding scoping
- laravel/laravel: 13.x application skeleton
- OWASP Top 10: Broken Access Control
Originally published on DEV Talk.
