In plain PHP (with no framework), the edit-review page is usually guarded by one if: if ($review['user_id'] != $_SESSION['user_id']) { die('Forbidden'); }. The delete page needs a similar if that's a little different, because librarians may delete too. Once there are five pages, the rules are spread over five files, and in one of them the check is missing.
Authentication answers the question "who are you". Next, authorization answers "may you do this to this piece of data". In Laravel, the authorization rules for one model are gathered in one class called a Policy. Think of a hotel key card. The front desk already knows who you are (authentication), but your card only opens room 207, your own room (authorization). Housekeeping may enter any room to clean it, but may not change your things. The manager has a master card that opens every door. In the Library app below, your room is the review you wrote, housekeeping is the librarian, and the master card belongs to the head librarian.
The rules: book reviews in the Library
Members may write book reviews (the Review model, a reviews table, with a user_id column that holds the author's id). The rules:
- Everyone, guests who haven't logged in included, may read the list of reviews.
- Only the author may change a review, because the words are theirs.
- The author or a librarian (
is_admin) may delete a review, for example a review that is spam. - The head librarian (
is_super_admin) may do everything.
Who is logged in is already handled by the auth middleware (the Middleware lesson): a guest who opens a page guarded by auth is sent to /login. The policy works after that middleware. Roles and permissions in general are covered in the Role-based Access Control (RBAC) and RBAC vs ABAC: Implementation lessons (Auth track).
Your first policy
Make the policy with Artisan:
php artisan make:policy ReviewPolicy --model=Review
This is the policy for reviews, with the rules above:
<?php
// app/Policies/ReviewPolicy.php
namespace App\Policies;
use App\Models\Review;
use App\Models\User;
class ReviewPolicy
{
public function before(User $user, string $ability): ?bool
{
if ($user->is_super_admin) {
return true; // master card: may do everything
}
return null; // go on to the action's method
}
public function viewAny(?User $user): bool
{
return true; // guests may read the list too
}
public function update(User $user, Review $review): bool
{
return $user->id === $review->user_id;
}
public function delete(User $user, Review $review): bool
{
return $user->id === $review->user_id || $user->is_admin;
}
}
make:policy ReviewPolicy --model=Reviewcreates the file inapp/PolicieswithviewAny,view,create,update,delete, and a few more methods already in it. Delete the ones you don't use.- Laravel finds this policy by itself from its name: the
Reviewmodel is inapp/Models, so its policy isReviewPolicyinapp/Policies. This policy doesn't need to be registered. - Each action has one method, which returns
true(allowed) orfalse(not allowed). The action's name, for example'update', is the same as the method's name. In the code, an action is called an ability ($ability). $user->id === $review->user_idchecks whether the logged-in user is the review's author. This ownership check is in almost every policy.?User $useronviewAnymeans$usermay benull(a guest), so guests are checked by this method too. Without the?, Laravel refuses guests right away, without calling the method.before()runs first, before the action's method.truemeans allowed with no further checks,falsemeans refused, andnullmeans go on to the action's method.before()is only called when the policy has a method for that action.
Here is the outcome when five people try to change and delete review #7, written by Budi (id 1):
| User | before() |
update |
delete |
|---|---|---|---|
| Budi, its author | null |
1 === 1, allowed |
allowed |
| Ani (id 2), another member | null |
2 === 1, refused |
refused |
| Rina, a librarian | null |
refused | allowed, because is_admin |
| Mr. Dodi, head librarian | true |
allowed, update() isn't called |
allowed |
| A guest | not called | refused | refused |
Three places to use a policy
A policy is used in three places. Their numbers are in the comment of each piece of code:
// 1. In the controller: throw a 403 when not allowed
public function update(UpdateReviewRequest $request, Review $review)
{
Gate::authorize('update', $review); // calls ReviewPolicy::update()
$review->update($request->validated());
return redirect()->route('reviews.index');
}
{{-- 2. In Blade: show the button only when allowed --}}
@can('update', $review)
<a href="{{ route('reviews.edit', $review) }}">Edit</a>
@endcan
// 3. In plain code: get true or false, without throwing anything
if (Gate::allows('delete', $review)) {
// ...
}
Gateis the part of Laravel that runs permission checks.Gate::authorize('update', $review)asksReviewPolicy::update(). When the answer isfalse,Gate::authorize()throws an exception, and Laravel answers with the page403 | This action is unauthorized.(or{"message":"This action is unauthorized."}for a JSON request).$this->authorize('update', $review)means the same, but needs theAuthorizesRequeststrait. From Laravel 11 on,app/Http/Controllers/Controller.php(the parent class of every controller) is empty, so adduse AuthorizesRequests;there first.@can('update', $review)and$request->user()->can('update', $review)only ask, without refusing any request.- A policy works on a route too:
->can('update', 'review')answers 403 before the controller is called.'review'here is the name of the{review}parameter in that route.
@can only hides the button
@can only decides what is visible on the page. A request can still be sent without pressing the button. Ani is logged in, so she has her own session cookie and CSRF token. With them, she can send PUT /reviews/7 (Budi's review) with curl (a program that sends requests from the terminal), Postman, or the browser's devtools. If the controller doesn't call Gate::authorize(), Ani's request is accepted, and Ani manages to change Budi's review. Not a 403, and not a 404 either.
So always check the permission on the server: in the controller, in the route, or in a FormRequest's authorize(). Use @can only to keep the page tidy.
Gates for rules without a model
Not every rule is about one record (one row of data, such as one review). The rule "Only librarians may open the monthly report" is written as a Gate: a named rule registered with Gate::define() in AppServiceProvider::boot():
Gate::define('view-reports', fn (User $user) => $user->is_admin);
// then anywhere
Gate::authorize('view-reports');
So a rule about one model (a review, a loan) goes into a Policy. A rule about one feature goes into a Gate.
⚠️ Rules that exist but never get used
- Only
@can, no check on the server. The button is gone, but the address stays open to anyone who knows it. $this->authorize()on Laravel 11 or later without the trait. You get the errorCall to undefined method ...::authorize(). UseGate::authorize(), or adduse AuthorizesRequests;to the parent classController.before()returningfalsewhen you meant "go on".falserefuses every action, including an author changing their own review. To go on to the action's method, returnnull.- Names that don't match. The
Reviewmodel needsReviewPolicyinapp/Policies, and the'update'action calls theupdate()method. If even one letter is wrong, the rule is never used.
TL;DR: A Policy holds the "allowed or not" rules (authorization) for one model. Make it with php artisan make:policy ReviewPolicy --model=Review. Each action has one method that returns true (allowed) or false (not allowed), usually with the ownership check $user->id === $review->user_id. before() runs first: true allows every action, false refuses every action, null goes on to the action's method. On the server, use Gate::authorize('update', $review) or $this->authorize(...) (needs the AuthorizesRequests trait): when it's not allowed, Laravel answers 403 | This action is unauthorized.. Use @can in Blade to hide buttons, and Gate::allows() to just ask. @can alone protects nothing: a request sent directly is still accepted when the server doesn't check.
⚡ One method per action
Write:
public function update(User $user, Review $review): bool
{
return $user->id === $review->user_id;
}
Meaning: A policy is a class that holds the "allowed or not" rules for one model, here Review (a book review). php artisan make:policy ReviewPolicy --model=Review creates the policy, and Laravel finds it by itself from its name. Each action has a method that returns true (allowed) or false (not allowed). This update method lets a user change a review only when they are its author: the user's id equals the review's user_id. This ownership check is in almost every policy.
⚡ before() runs first
Write:
public function before(User $user, string $ability): ?bool
{
if ($user->is_super_admin) {
return true;
}
return null;
}
Guess first: before() runs before an action method such as update(), and any answer other than null becomes the final answer right away. If before() returns false for an ordinary member, not null, can a review's author still change their own review?
No. false refuses every action, and update() is not called anymore. To go on to the action's method, return null.
Meaning: Here the head librarian (is_super_admin) gets true: allowed to do every action with no more checks, like a hotel's master card that opens every door. Other users get null: go on to update() or delete().
In the exercise, fill in the bodies of PostPolicy's methods before, update and delete.
⚡ @can only hides the button
Write:
Gate::authorize('update', $review);
Guess first: @can in Blade shows the Edit button only to users who are allowed. Ani (another member) doesn't see the Edit button on Budi's review, and the controller checks nothing. Can Ani change Budi's review?
Yes. Ani just sends the PUT directly with curl, Postman or the browser's devtools, and the request is accepted. Not a 403.
Meaning: Always check the permission on the server, with the line above inside the controller. Gate::authorize('update', $review) asks the policy, then answers 403 | This action is unauthorized. when the policy says no. @can only keeps the page tidy.