Laravel Reference
Examples are written for Laravel 11 and 12 and tested against Laravel 12. They don't assume anything about your base controller: a fresh Laravel application's App\Http\Controllers\Controller is an empty class, so helpers such as $this->authorize() aren't available unless you add them (see authorizeResource()). For the full reference, see the official Laravel authorization documentation.
Gates vs policies
A gate is a simple closure-based authorization check, good for actions that aren't tied to a specific model (e.g. "can view the admin panel"). A policy groups all the authorization logic for one model — and is what most apps end up using once there's more than a rule or two.
Both answer the same question — may this user do this? — and both are checked the same ways (Gate::authorize(), can middleware, @can in Blade), so you can mix them. Authorization is separate from authentication: middleware like auth decides who someone is, and a gate or policy decides what they may do.
Gates
// AppServiceProvider::boot()
Gate::define('view-admin-panel', function (User $user) {
return $user->role === 'admin';
});
if (Gate::allows('view-admin-panel')) {
// ...
}
Gate::authorize('view-admin-panel'); // throws 403 automatically if denied
Creating a policy
php artisan make:policy PostPolicy --model=Post
class PostPolicy
{
public function view(User $user, Post $post): bool
{
return $post->published || $user->id === $post->user_id;
}
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->role === 'admin';
}
}
The update and delete methods above show the two most common patterns: ownership-based (the user created the record) and role-based (an admin can do it regardless). Policies are resolved through the service container, so you can type-hint dependencies in the constructor.
Registering policies
Laravel auto-discovers a policy named {Model}Policy for a given model — no manual registration needed in modern Laravel versions — as long as the policy lives in a Policies directory at or above the model's directory. With models in app/Models, that means app/Policies (or app/Models/Policies), so App\Models\Post maps to App\Policies\PostPolicy.
When a policy isn't in the conventional location or doesn't follow the {Model}Policy naming, register it explicitly instead of relying on auto-discovery:
// AppServiceProvider::boot()
Gate::policy(Post::class, CustomPostPolicy::class);
Laravel 12 also lets the model name its policy with an attribute:
use App\Policies\CustomPostPolicy;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
#[UsePolicy(CustomPostPolicy::class)]
class Post extends Model
{
// ...
}
Authorizing in controllers
The most direct approach is Gate::authorize(). It works in any controller — including one that extends nothing — and throws an AuthorizationException, which Laravel turns into a 403 response:
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
class PostController extends Controller
{
public function update(Request $request, Post $post)
{
Gate::authorize('update', $post); // 403s automatically if denied
// ...
}
public function store(Request $request)
{
// No model instance exists yet, so pass the class name.
Gate::authorize('create', Post::class);
// ...
}
}
Here $post comes from route model binding, and a controller method is the natural place for the check. You can also ask the user directly, anywhere you have a user instance:
if ($user->can('update', $post)) {
// ...
}
if ($user->cannot('delete', $post)) {
abort(403);
}
// Or from a request:
if ($request->user()->cannot('update', $post)) {
abort(403);
}
Authorizing in routes with the can middleware
A route can authorize a request before it ever reaches the controller by using the can middleware alias, which Laravel registers for you. Either of these is equivalent:
Route::put('/posts/{post}', [PostController::class, 'update'])
->can('update', 'post');
Route::put('/posts/{post}', [PostController::class, 'update'])
->middleware('can:update,post');
// Abilities that take no model instance pass the class instead
Route::post('/posts', [PostController::class, 'store'])
->can('create', Post::class);
The second argument (post) is the route parameter name, not the model class. Laravel resolves it through route model binding and passes the model to the policy method, so it must match the {post} placeholder exactly. See the middleware guide for how middleware is applied to routes and groups.
Authorizing with HasMiddleware
In Laravel 11 and 12, a controller can declare its own middleware by implementing HasMiddleware, so authorization sits next to the actions it protects. It doesn't need a base class:
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
class PostController implements HasMiddleware
{
public static function middleware(): array
{
return [
'auth',
new Middleware('can:update,post', only: ['edit', 'update']),
new Middleware('can:delete,post', only: ['destroy']),
new Middleware('can:create,'.Post::class, only: ['create', 'store']),
];
}
// ...
}
On Laravel 10 and earlier, call $this->middleware('can:update,post')->only(['edit', 'update']) in the constructor instead.
Authorizing resource routes
A policy's method names line up with the seven resource controller actions — viewAny, view, create, update, delete, plus restore and forceDelete for soft-deleted models. One way to authorize all of them is on the resource route itself, using middlewareFor() (documented for Laravel 12):
Route::resource('posts', PostController::class)
->middlewareFor('index', 'can:viewAny,'.Post::class)
->middlewareFor(['create', 'store'], 'can:create,'.Post::class)
->middlewareFor('show', 'can:view,post')
->middlewareFor(['edit', 'update'], 'can:update,post')
->middlewareFor('destroy', 'can:delete,post');
Note that viewAny and create don't receive a model instance — there's nothing to check ownership against yet — so those two methods only take the $user argument.
authorizeResource()
authorizeResource() is still supported and does the same job in one line from a controller's constructor. It needs two things a fresh Laravel 11 or 12 application does not give its base controller: the AuthorizesRequests trait, and a parent class that provides middleware() (Illuminate\Routing\Controller). Without both, calling it fails with an undefined-method error.
use App\Models\Post;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Routing\Controller;
class PostController extends Controller
{
use AuthorizesRequests;
public function __construct()
{
$this->authorizeResource(Post::class, 'post');
}
}
To make authorizeResource() and $this->authorize() available in every controller, add the same use statements to your own App\Http\Controllers\Controller and have it extend Illuminate\Routing\Controller. The second argument is the route parameter name. Each controller action maps to a policy ability:
| Controller action | Policy method | Receives a model? |
|---|---|---|
| index | viewAny | No (class) |
| show | view | Yes |
| create, store | create | No (class) |
| edit, update | update | Yes |
| destroy | delete | Yes |
In Blade
See the Blade templating guide for the rest of Blade's directives.
@can('update', $post)
<a href="/posts/{{ $post->id }}/edit">Edit</a>
@endcan
@cannot('delete', $post)
<p>You cannot delete this post.</p>
@endcannot
{{-- No model instance exists yet — pass the class name instead --}}
@can('create', App\Models\Post::class)
<a href="/posts/create">New post</a>
@endcan
Hiding a link is a convenience, not security: always enforce the same rule on the server with Gate::authorize() or the can middleware.
Authorizing in Form Requests
class UpdatePostRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('update', $this->route('post'));
}
}
Because a Form Request's authorize() method runs before validation, a denied request fails fast with a 403 and never touches the validation rules. This is a good place to check ownership or role-based access without cluttering the controller method itself.
Gate::before and Gate::after
Both gates and policies can be short-circuited globally. A common use is granting a super-admin role blanket access without having to repeat that check in every single policy method:
// AppServiceProvider::boot()
Gate::before(function (User $user, string $ability) {
if ($user->isAdmin()) {
return true; // skips the specific gate/policy check entirely
}
});
Gate::after(function (User $user, string $ability, ?bool $result, mixed $arguments) {
// Runs after every check, even ones already resolved by before().
// Useful for auditing/logging authorization decisions.
});
Returning null (or nothing) from a before callback lets the normal gate or policy method decide as usual; returning true or false overrides it immediately. To limit the same idea to one model, define a before(User $user, string $ability) method on the policy class instead.
Custom denial messages
By default a failed authorization check just throws a generic 403. To surface a more specific reason to the user, return a Response object from the policy method instead of a boolean:
use Illuminate\Auth\Access\Response;
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::deny('You do not own this post.');
}
The custom message is available on the caught AuthorizationException and is what gets shown when Gate::authorize() aborts the request. Use Gate::inspect('update', $post) to get the full response without throwing, and Response::denyAsNotFound() to answer with a 404 instead, so you don't reveal that the record exists.
Testing authorization
Assert directly against can()/cannot() without going through a route, or check the response of a feature test that hits an authorized endpoint:
public function test_only_the_owner_can_update_a_post(): void
{
$owner = User::factory()->create();
$post = Post::factory()->for($owner)->create();
$this->assertTrue($owner->can('update', $post));
$stranger = User::factory()->create();
$this->assertFalse($stranger->can('update', $post));
$this->actingAs($stranger)
->put("/posts/{$post->id}", ['title' => 'Hacked'])
->assertForbidden();
}
Testing the route as well as the policy catches a missing can middleware or a wrong route parameter name, which a policy-only test can't see.
Common mistakes and troubleshooting
Call to undefined method authorize()orauthorizeResource(). Your base controller doesn't useAuthorizesRequests, which fresh Laravel 11 and 12 applications don't include. UseGate::authorize(), thecanmiddleware, or add the trait and parent class.- Everything returns 403. If no policy is found for the model and no gate has that name, the check fails closed. Check the policy's name and location, or register it with
Gate::policy(). Also check the ability name: a controller'seditaction is authorized by the policy'supdatemethod,showbyview,indexbyviewAny, andstorebycreate. can:update,postdoesn't work. The second value must match the route parameter name exactly. Runphp artisan route:listto see the real name — a resource namedblog-posts, for example, has a{blog_post}parameter.- Guests are always denied. Gates and policies return
falsefor unauthenticated users unless the user argument is nullable (?User $user). Put theauthmiddleware first so guests are redirected to log in instead of seeing a 403. - Returning
falsefrombefore. That denies everything. Returntrueto allow, ornullto fall through to the normal check. - Passing an instance to a no-model ability.
viewAnyandcreateare authorized against the class (Post::class), not an instance.
Related guides
Authorization usually sits between a few other building blocks: middleware to attach it to routes, controllers to apply it per action, validation and Form Requests to combine it with input checks, Eloquent models to define what a policy protects, and testing to prove it works.