How can you declare controller middleware directly on a class using attributes in Laravel 13?

In Laravel 13, you can declare controller middleware directly on a class (or individual methods) using the new native PHP #[Middleware] attribute. This provides a declarative approach, keeping your middleware and authorization rules collocated with the controller logic instead of in a separate constructor or route file.

Syntax and Usage

You need to import the Middleware attribute from the IlluminateRoutingAttributesControllers namespace. You can stack multiple attributes if a controller requires multiple middleware layers.

namespace AppHttpControllers;

use IlluminateRoutingAttributesControllersMiddleware;
// Optional: Use the Authorize attribute for policy checks
use IlluminateRoutingAttributesControllersAuthorize;
use AppModelsPost;

// Apply middleware to the entire class
#[Middleware( auth )]
#[Middleware( admin )]
class AdminController extends Controller
{
   public function index()
   {
       // ...
   }

   // You can also apply middleware to specific methods
   #[Middleware( verified )]
   #[Authorize( create , [Post::class])]
   public function store()
   {
       // ...
   }
}

Key Details

  • Attribute vs. Constructor: Instead of using $this->middleware( auth ) inside the __construct()method (the traditional way), the attribute approach makes the security requirements instantly visible right above the class or method name .
  • Method-Level Control: Just like class-level declarations, placing #[Middleware] above a specific method ensures that middleware only runs for that particular action, giving you fine-grained control .
  • Laravel 13 Requirement: This feature is part of Laravel 13 is expanded first-party PHP attribute support. Note that Laravel 13 requires a minimum PHP version of 8.3 .


 

3 Views