Skip to content

Authorization

Security

Authorization

Introduction

While authentication identifies who the current user is, authorization determines which actions they are permitted to perform. For example, in a blog application, any user may read a published post, while only its author may edit or delete it.

Laravel organizes authorization rules into policies. Each policy is a struct whose methods define abilities (such as update or delete) for a specific model or resource. Because you pass the policy method itself when checking an ability, misspelled names or mismatched model types are caught at compile time:

1user.authorize(PostPolicy::update, &post).await?;
1user.authorize(PostPolicy::update, &post).await?;

Writing policies

Define a policy by annotating an impl block with #[policy], typically on a unit struct named after the model. Each method accepts the user first, followed by the model (if applicable), and returns whether the action is allowed.

For example, suppose each Post model stores the author's user_id. This policy (placed in src/policies/post.rs, or directly alongside the model in src/models/post.rs) allows only the author to update or delete a post:

1use laravel::auth::policy;
2 
3use crate::models::{Post, User};
4 
5pub struct PostPolicy;
6 
7#[policy]
8impl PostPolicy {
9 pub fn update(user: &User, post: &Post) -> bool {
10 user.id == post.user_id
11 }
12 
13 pub fn delete(user: &User, post: &Post) -> bool {
14 user.id == post.user_id
15 }
16}
1use laravel::auth::policy;
2 
3use crate::models::{Post, User};
4 
5pub struct PostPolicy;
6 
7#[policy]
8impl PostPolicy {
9 pub fn update(user: &User, post: &Post) -> bool {
10 user.id == post.user_id
11 }
12 
13 pub fn delete(user: &User, post: &Post) -> bool {
14 user.id == post.user_id
15 }
16}

If you define a policy alongside its model in src/models/post.rs, re-export it from src/models/mod.rs:

1// src/models/mod.rs
2mod post;
3mod user;
4 
5pub use post::{Post, PostFactory, PostPolicy};
6pub use user::{User, UserFactory};
1// src/models/mod.rs
2mod post;
3mod user;
4 
5pub use post::{Post, PostFactory, PostPolicy};
6pub use user::{User, UserFactory};

If you prefer keeping policies in their own src/policies directory, declare the policies module in src/lib.rs (as adding your own modules describes) and re-export each policy from src/policies/mod.rs:

1// src/lib.rs
2pub mod policies;
3 
4// src/policies/mod.rs
5mod post;
6 
7pub use post::PostPolicy;
1// src/lib.rs
2pub mod policies;
3 
4// src/policies/mod.rs
5mod post;
6 
7pub use post::PostPolicy;

Name each method after the action it allows. The usual names are view_any, view, create, update, delete, restore, and force_delete, but you may add any ability your application needs.

Because #[policy] treats every function in the block as an ability, place shared helper functions in a separate impl block without #[policy]:

1#[policy]
2impl PostPolicy {
3 pub fn update(user: &User, post: &Post) -> bool {
4 Self::owns(user, post)
5 }
6 
7 pub fn delete(user: &User, post: &Post) -> bool {
8 Self::owns(user, post)
9 }
10}
11 
12impl PostPolicy {
13 fn owns(user: &User, post: &Post) -> bool {
14 user.id == post.user_id
15 }
16}
1#[policy]
2impl PostPolicy {
3 pub fn update(user: &User, post: &Post) -> bool {
4 Self::owns(user, post)
5 }
6 
7 pub fn delete(user: &User, post: &Post) -> bool {
8 Self::owns(user, post)
9 }
10}
11 
12impl PostPolicy {
13 fn owns(user: &User, post: &Post) -> bool {
14 user.id == post.user_id
15 }
16}

Policy responses

A policy method returning false denies the action with a 403 status and the default message "This action is unauthorized." To return a custom denial message instead, return an Access response using Access::allow() and Access::deny(..):

1use laravel::auth::{Access, policy};
2 
3#[policy]
4impl PostPolicy {
5 pub fn update(user: &User, post: &Post) -> Access {
6 if user.id == post.user_id {
7 Access::allow()
8 } else {
9 Access::deny("You do not own this post.")
10 }
11 }
12}
1use laravel::auth::{Access, policy};
2 
3#[policy]
4impl PostPolicy {
5 pub fn update(user: &User, post: &Post) -> Access {
6 if user.id == post.user_id {
7 Access::allow()
8 } else {
9 Access::deny("You do not own this post.")
10 }
11 }
12}

When you want to hide whether a record exists from unauthorized users (such as another team's private project), return Access::deny_as_not_found(), which responds with a 404 status instead of 403:

1#[policy]
2impl ProjectPolicy {
3 pub fn view(user: &User, project: &Project) -> Access {
4 if user.team_id == project.team_id {
5 Access::allow()
6 } else {
7 Access::deny_as_not_found()
8 }
9 }
10}
1#[policy]
2impl ProjectPolicy {
3 pub fn view(user: &User, project: &Project) -> Access {
4 if user.team_id == project.team_id {
5 Access::allow()
6 } else {
7 Access::deny_as_not_found()
8 }
9 }
10}

If you need a different HTTP status code altogether, call Access::deny_with_status(..), which responds with that status code and its standard reason phrase:

1Access::deny_with_status(401)
1Access::deny_with_status(401)

Abilities without a record

Some abilities don't involve a record yet, such as creating a post. Their methods take only the user. This one lets users create posts once they've verified their email:

1#[policy]
2impl PostPolicy {
3 pub fn create(user: &User) -> bool {
4 user.email_verified_at.is_some()
5 }
6 
7 // ...
8}
1#[policy]
2impl PostPolicy {
3 pub fn create(user: &User) -> bool {
4 user.email_verified_at.is_some()
5 }
6 
7 // ...
8}

Abilities that don't involve a specific model, such as viewing an admin dashboard, go in their own policy. For example, suppose your users have an is_admin column:

1use laravel::auth::policy;
2 
3use crate::models::User;
4 
5pub struct AdminPolicy;
6 
7#[policy]
8impl AdminPolicy {
9 pub fn view_dashboard(user: &User) -> bool {
10 user.is_admin
11 }
12}
1use laravel::auth::policy;
2 
3use crate::models::User;
4 
5pub struct AdminPolicy;
6 
7#[policy]
8impl AdminPolicy {
9 pub fn view_dashboard(user: &User) -> bool {
10 user.is_admin
11 }
12}

Guests

By default, a policy method accepting &User automatically denies guests without running. To evaluate guests explicitly, accept Option<&User>, which receives None for unauthenticated visitors. For example, suppose posts have a published column so anyone may view published posts while only authors may view drafts:

1#[policy]
2impl PostPolicy {
3 pub fn view(user: Option<&User>, post: &Post) -> bool {
4 post.published || user.is_some_and(|user| user.id == post.user_id)
5 }
6 
7 // ...
8}
1#[policy]
2impl PostPolicy {
3 pub fn view(user: Option<&User>, post: &Post) -> bool {
4 post.published || user.is_some_and(|user| user.id == post.user_id)
5 }
6 
7 // ...
8}

Allowing administrators everything

Sometimes you may have administrators who are permitted to perform every action a policy covers. Rather than check is_admin in every method, add a before method. It takes the user and returns an Option<bool>:

1#[policy]
2impl PostPolicy {
3 fn before(user: &User) -> Option<bool> {
4 user.is_admin.then_some(true)
5 }
6 
7 // ...
8}
1#[policy]
2impl PostPolicy {
3 fn before(user: &User) -> Option<bool> {
4 user.is_admin.then_some(true)
5 }
6 
7 // ...
8}

The before method executes automatically before every other method in the policy:

  • Returning Some(true) immediately grants permission without running the requested ability method.
  • Returning Some(false) immediately denies permission.
  • Returning None falls through to the requested ability method (such as update or delete) so it can decide for itself.

Because before receives &User, it is skipped for unauthenticated guests, allowing guest-accessible methods that accept Option<&User> to evaluate guests directly.

If your before check needs to know which ability is being evaluated (for example, allowing administrators everything except permanently deleting posts), accept the method's name as a second &str parameter:

1#[policy]
2impl PostPolicy {
3 fn before(user: &User, ability: &str) -> Option<bool> {
4 if ability == "force_delete" {
5 return None;
6 }
7 
8 user.is_admin.then_some(true)
9 }
10 
11 // ...
12}
1#[policy]
2impl PostPolicy {
3 fn before(user: &User, ability: &str) -> Option<bool> {
4 if ability == "force_delete" {
5 return None;
6 }
7 
8 user.is_admin.then_some(true)
9 }
10 
11 // ...
12}

Asynchronous checks

When an authorization check needs to query the database, make the policy method async and return laravel::Result. For example, this policy allows authors to delete a post only while it has no comments:

1use laravel::auth::{Access, policy};
2 
3use crate::models::{Comment, Post, User};
4 
5#[policy]
6impl PostPolicy {
7 pub async fn delete(user: &User, post: &Post) -> laravel::Result<Access> {
8 if user.id != post.user_id {
9 return Ok(Access::deny("You do not own this post."));
10 }
11 
12 if Comment::query().filter(Comment::post_id.eq(post.id)).exists().await? {
13 return Ok(Access::deny("You can't delete a post with comments."));
14 }
15 
16 Ok(Access::allow())
17 }
18 
19 // ...
20}
1use laravel::auth::{Access, policy};
2 
3use crate::models::{Comment, Post, User};
4 
5#[policy]
6impl PostPolicy {
7 pub async fn delete(user: &User, post: &Post) -> laravel::Result<Access> {
8 if user.id != post.user_id {
9 return Ok(Access::deny("You do not own this post."));
10 }
11 
12 if Comment::query().filter(Comment::post_id.eq(post.id)).exists().await? {
13 return Ok(Access::deny("You can't delete a post with comments."));
14 }
15 
16 Ok(Access::allow())
17 }
18 
19 // ...
20}

If an asynchronous policy method returns an Err (such as from a failed database query), Laravel fails the request with a 500 server error rather than treating it as an authorization denial.

Checking abilities

Once your policy is defined, check abilities in your handlers using authorize or can on your user type, passing the policy method followed by any additional arguments.

In a handler, extract the signed-in user with Authenticated<User> and resolve the target model via route model binding:

1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5use crate::policies::post::PostPolicy;
6 
7pub async fn edit(
8 user: Authenticated<User>,
9 post: Post,
10) -> laravel::Result<Page> {
11 user.authorize(PostPolicy::update, &post).await?;
12 
13 Ok(inertia::render("Posts/Edit", props! { "post" => &post }))
14}
15 
16pub async fn show(
17 user: Authenticated<User>,
18 post: Post,
19) -> laravel::Result<Page> {
20 let can_delete = user.can(PostPolicy::delete, &post).await?;
21 
22 Ok(inertia::render("Posts/Show", props! { "post" => &post, "canDelete" => can_delete }))
23}
1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5use crate::policies::post::PostPolicy;
6 
7pub async fn edit(
8 user: Authenticated<User>,
9 post: Post,
10) -> laravel::Result<Page> {
11 user.authorize(PostPolicy::update, &post).await?;
12 
13 Ok(inertia::render("Posts/Edit", props! { "post" => &post }))
14}
15 
16pub async fn show(
17 user: Authenticated<User>,
18 post: Post,
19) -> laravel::Result<Page> {
20 let can_delete = user.can(PostPolicy::delete, &post).await?;
21 
22 Ok(inertia::render("Posts/Show", props! { "post" => &post, "canDelete" => can_delete }))
23}

authorize returns an error when denied so ? aborts the handler with the configured status and message, while can returns a bool so you can branch on it yourself.

Both methods come from the Authorizable trait imported by the prelude and automatically implemented for every Authenticatable model.

For abilities that do not take a model or any additional arguments beyond the user (such as PostPolicy::create), pass () as the second argument:

1pub async fn create(user: Authenticated<User>) -> laravel::Result<Page> {
2 user.authorize(PostPolicy::create, ()).await?;
3 
4 Ok(inertia::render("Posts/Create", props! {}))
5}
1pub async fn create(user: Authenticated<User>) -> laravel::Result<Page> {
2 user.authorize(PostPolicy::create, ()).await?;
3 
4 Ok(inertia::render("Posts/Create", props! {}))
5}

Authorizing via Auth or Request

When a route is accessible to guests as well as signed-in users, call can or authorize on Auth<User> or Request:

1use laravel::auth::Auth;
2use laravel::inertia::Page;
3use laravel::prelude::*;
4 
5use crate::models::{Post, User};
6use crate::policies::post::PostPolicy;
7 
8pub async fn show(auth: Auth<User>, post: Post) -> laravel::Result<Page> {
9 auth.authorize(PostPolicy::view, &post).await?;
10 
11 // ...
12}
13 
14pub async fn create(request: Request) -> laravel::Result<Page> {
15 request.authorize(PostPolicy::create, ()).await?;
16 
17 // ...
18}
1use laravel::auth::Auth;
2use laravel::inertia::Page;
3use laravel::prelude::*;
4 
5use crate::models::{Post, User};
6use crate::policies::post::PostPolicy;
7 
8pub async fn show(auth: Auth<User>, post: Post) -> laravel::Result<Page> {
9 auth.authorize(PostPolicy::view, &post).await?;
10 
11 // ...
12}
13 
14pub async fn create(request: Request) -> laravel::Result<Page> {
15 request.authorize(PostPolicy::create, ()).await?;
16 
17 // ...
18}

Guests receive a 403 from authorize and false from can unless the policy method accepts Option<&User>.

Passing more arguments

A policy method may accept up to three additional arguments after the user when a decision depends on multiple models. For example, suppose an author may move a post into a Category only if that category is unlocked:

1use laravel::auth::policy;
2 
3use crate::models::{Category, Post, User};
4 
5#[policy]
6impl PostPolicy {
7 pub fn move_to(user: &User, post: &Post, category: &Category) -> bool {
8 user.id == post.user_id && !category.locked
9 }
10 
11 // ...
12}
1use laravel::auth::policy;
2 
3use crate::models::{Category, Post, User};
4 
5#[policy]
6impl PostPolicy {
7 pub fn move_to(user: &User, post: &Post, category: &Category) -> bool {
8 user.id == post.user_id && !category.locked
9 }
10 
11 // ...
12}

Pass two or three arguments as a tuple, in the method's order:

1user.authorize(PostPolicy::move_to, (&post, &category)).await?;
1user.authorize(PostPolicy::move_to, (&post, &category)).await?;

Authorizing a form

A form type can authorize the incoming request automatically using #[validate(authorize(..))], so your handler does not need to call authorize itself. When the policy method expects a model (such as Post on a /posts/{post} route), pass route("post") to resolve that route parameter and pass the model to the policy:

1use laravel::prelude::*;
2 
3use crate::models::Post;
4use crate::policies::post::PostPolicy;
5 
6#[laravel::input]
7#[validate(authorize(PostPolicy::update, route("post")))]
8pub struct UpdatePost {
9 #[validate(required, max_length(255))]
10 title: String,
11}
12 
13pub async fn update(post: Post, Valid(input): Valid<UpdatePost>) -> laravel::Result<Redirect> {
14 // Only users who may update the post get here, with a valid title...
15 
16 Ok(Redirect::back())
17}
1use laravel::prelude::*;
2 
3use crate::models::Post;
4use crate::policies::post::PostPolicy;
5 
6#[laravel::input]
7#[validate(authorize(PostPolicy::update, route("post")))]
8pub struct UpdatePost {
9 #[validate(required, max_length(255))]
10 title: String,
11}
12 
13pub async fn update(post: Post, Valid(input): Valid<UpdatePost>) -> laravel::Result<Redirect> {
14 // Only users who may update the post get here, with a valid title...
15 
16 Ok(Redirect::back())
17}

Valid<UpdatePost> checks PostPolicy::update for the current user before it validates the input. A user who may not update the post gets the denial's response, not validation errors.

For an ability without a record, leave out the arguments, as in #[validate(authorize(PostPolicy::create))]. List several records in the method's order, as in authorize(PostPolicy::move_to, route("post"), route("category")).

Checking types other than users

A policy may decide abilities for a type other than your user, such as a team whose plan limits how many projects it has. Implement Authorizable for the type with an empty impl, and write the policy with the type first:

1use laravel::auth::{Authorizable, policy};
2 
3use crate::models::Team;
4 
5impl Authorizable for Team {}
6 
7pub struct ProjectPolicy;
8 
9#[policy]
10impl ProjectPolicy {
11 pub fn create(team: &Team) -> bool {
12 team.projects_count < team.project_limit
13 }
14}
1use laravel::auth::{Authorizable, policy};
2 
3use crate::models::Team;
4 
5impl Authorizable for Team {}
6 
7pub struct ProjectPolicy;
8 
9#[policy]
10impl ProjectPolicy {
11 pub fn create(team: &Team) -> bool {
12 team.projects_count < team.project_limit
13 }
14}

Then check the team as you would a user, such as in a handler for the route /teams/{team}/projects:

1pub async fn store(team: Team) -> laravel::Result<Redirect> {
2 team.authorize(ProjectPolicy::create, ()).await?;
3 
4 // ...
5}
1pub async fn store(team: Team) -> laravel::Result<Redirect> {
2 team.authorize(ProjectPolicy::create, ()).await?;
3 
4 // ...
5}

Every method of a policy takes the same type first. To check abilities for both users and teams, write a policy for each.

Sharing abilities with the frontend

Your pages often need to know what the user may do, so they can hide an Edit button from someone who cannot edit. Check the abilities on the server and pass the results to your views or Inertia pages.

In views

For server-rendered views, evaluate the abilities in your handler and pass them through data!:

1use laravel::prelude::*;
2use laravel::view::View;
3 
4use crate::models::{Post, User};
5use crate::policies::post::PostPolicy;
6 
7pub async fn show(user: Authenticated<User>, post: Post) -> laravel::Result<View> {
8 let can = data! {
9 update => user.can(PostPolicy::update, &post).await?,
10 delete => user.can(PostPolicy::delete, &post).await?,
11 };
12 
13 Ok(view("posts.show", data! { post, can }))
14}
1use laravel::prelude::*;
2use laravel::view::View;
3 
4use crate::models::{Post, User};
5use crate::policies::post::PostPolicy;
6 
7pub async fn show(user: Authenticated<User>, post: Post) -> laravel::Result<View> {
8 let can = data! {
9 update => user.can(PostPolicy::update, &post).await?,
10 delete => user.can(PostPolicy::delete, &post).await?,
11 };
12 
13 Ok(view("posts.show", data! { post, can }))
14}

Then branch on those booleans in your template:

1{% if can.update %}
2 <a href="/posts/{{ post.id }}/edit">Edit</a>
3{% endif %}
1{% if can.update %}
2 <a href="/posts/{{ post.id }}/edit">Edit</a>
3{% endif %}

For abilities that every template needs, share them for the current request with laravel::view::share inside a middleware.

With Inertia

With Inertia, pass the checked abilities as props:

1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3use serde_json::json;
4 
5use crate::models::{Post, User};
6use crate::policies::post::PostPolicy;
7 
8pub async fn show(
9 user: Authenticated<User>,
10 post: Post,
11) -> laravel::Result<Page> {
12 let can = json!({
13 "update": user.can(PostPolicy::update, &post).await?,
14 "delete": user.can(PostPolicy::delete, &post).await?,
15 });
16 
17 Ok(inertia::render("Posts/Show", props! { "post" => &post, "can" => can }))
18}
1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3use serde_json::json;
4 
5use crate::models::{Post, User};
6use crate::policies::post::PostPolicy;
7 
8pub async fn show(
9 user: Authenticated<User>,
10 post: Post,
11) -> laravel::Result<Page> {
12 let can = json!({
13 "update": user.can(PostPolicy::update, &post).await?,
14 "delete": user.can(PostPolicy::delete, &post).await?,
15 });
16 
17 Ok(inertia::render("Posts/Show", props! { "post" => &post, "can" => can }))
18}

For abilities that every page needs, such as whether the user may create posts, return them from your Inertia middleware's share method, in src/http/middleware:

1use laravel::http::Request;
2use laravel::inertia::{self, Props, props};
3use serde_json::json;
4 
5use crate::models::User;
6use crate::policies::post::PostPolicy;
7 
8impl inertia::Middleware for HandleInertiaRequests {
9 async fn share(&self, request: &Request) -> laravel::Result<Props> {
10 let user: Option<User> = request.user().await?;
11 
12 Ok(props! {
13 auth => json!({
14 "user": user,
15 "permissions": {
16 "post": { "create": request.can(PostPolicy::create, ()).await? },
17 },
18 }),
19 })
20 }
21}
1use laravel::http::Request;
2use laravel::inertia::{self, Props, props};
3use serde_json::json;
4 
5use crate::models::User;
6use crate::policies::post::PostPolicy;
7 
8impl inertia::Middleware for HandleInertiaRequests {
9 async fn share(&self, request: &Request) -> laravel::Result<Props> {
10 let user: Option<User> = request.user().await?;
11 
12 Ok(props! {
13 auth => json!({
14 "user": user,
15 "permissions": {
16 "post": { "create": request.can(PostPolicy::create, ()).await? },
17 },
18 }),
19 })
20 }
21}

A hidden button does not protect an endpoint, so the handler for the action must still call authorize.

Testing

To test a handler's authorization, send requests as different users with acting_as, and check each response:

1use laravel::model::create;
2use laravel::testing::prelude::*;
3 
4#[laravel::test]
5async fn only_the_author_may_update_a_post(app: Application) -> laravel::Result<()> {
6 let author = create!(User {
7 name: "Taylor",
8 email: "[email protected]",
9 password: "password",
10 })
11 .await?;
12 
13 let other = create!(User {
14 name: "Abigail",
15 email: "[email protected]",
16 password: "password",
17 })
18 .await?;
19 
20 let post = create!(Post { user_id: author.id, title: "Hello", published: true }).await?;
21 
22 app.put(format!("/posts/{}", post.id))
23 .acting_as(&other)
24 .json(json!({ "title": "Goodbye" }))
25 .await
26 .assert_forbidden()
27 .assert_json_path("message", "You do not own this post.");
28 
29 app.put(format!("/posts/{}", post.id))
30 .acting_as(&author)
31 .json(json!({ "title": "Goodbye" }))
32 .await
33 .assert_redirect();
34 
35 Ok(())
36}
1use laravel::model::create;
2use laravel::testing::prelude::*;
3 
4#[laravel::test]
5async fn only_the_author_may_update_a_post(app: Application) -> laravel::Result<()> {
6 let author = create!(User {
7 name: "Taylor",
8 email: "[email protected]",
9 password: "password",
10 })
11 .await?;
12 
13 let other = create!(User {
14 name: "Abigail",
15 email: "[email protected]",
16 password: "password",
17 })
18 .await?;
19 
20 let post = create!(Post { user_id: author.id, title: "Hello", published: true }).await?;
21 
22 app.put(format!("/posts/{}", post.id))
23 .acting_as(&other)
24 .json(json!({ "title": "Goodbye" }))
25 .await
26 .assert_forbidden()
27 .assert_json_path("message", "You do not own this post.");
28 
29 app.put(format!("/posts/{}", post.id))
30 .acting_as(&author)
31 .json(json!({ "title": "Goodbye" }))
32 .await
33 .assert_redirect();
34 
35 Ok(())
36}

A policy method is an ordinary function, so a unit test may also call it directly with records you build in the test, as in PostPolicy::update(&user, &post). before runs in a direct call too.