How can you declare an authorization policy check on a controller method using attributes in Laravel 13?

In Laravel 13, you can declare an authorization policy check directly on a controller method using the native #[Authorize] attribute. This attribute acts as syntactic sugar for the can middleware, allowing you to keep authorization logic collocated with your controller actions.

Syntax and Usage

You need to import the Authorize attribute from the IlluminateRoutingAttributesControllers namespace and place it above the method you want to protect.

namespace AppHttpControllers;

use AppModelsPost;
use IlluminateRoutingAttributesControllersAuthorize;

class PostController extends Controller
{
   // Basic usage: Ability and route parameter name
   #[Authorize( update , post )]
   public function update(Post $post)
   {
       // The current user is authorized to update the post...
   }

   // Passing an array for more complex policy arguments
   #[Authorize( create , [Comment::class, post ])]
   public function store(Post $post)
   {
       // ...
   }
}

Key Details

  • Parameters: The first argument is the ability (the policy method name, like update or delete ). The second argument is the model class or the route parameter name(like post ) that should be passed to the policy .
  • Automatic Resolution: When the request hits this method, Laravel resolves the route model binding (e.g., the Post $post instance) and automatically calls the corresponding policy method (e.g., PostPolicy::update()) with the authenticated user. If the policy returns false, Laravel throws a 403 Forbidden response .
  • Official vs. Packages: This is a first-party feature in Laravel 13 . You do not need to install third-party packages like jojomak13/laravel-attributes for basic policy checks, as the framework now handles this natively .
13 Views