Featured blog image
368 words 3 min read

Laravel New Approach to Controller Middleware

Among the important updates in Laravel 11, a new modification came in how to define Middleware inside Controllers, a change that reflects Laravel's continuous philosophy towards writing clearer, cleaner, and more organized code.


The Old Way (Before Laravel 11)

In previous versions, we used to define middleware inside the controller using the __construct() function like this:


class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only('index');
    }
}

This approach worked well, but it partially violated the principle of Separation of Concerns, because the main purpose of the __construct() function is to initialize the object, not to define request execution logic or access control.


The New Way in Laravel 11

In Laravel 11, a new interface named Illuminate\Routing\Controllers\HasMiddleware was introduced, which provides a clearer way to define middleware inside the controller:


use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class UserController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('auth', only: ['index']),
        ];
    }
}

This way, middleware definition is now done through a dedicated static function, without needing to use __construct().


Why This Change?


1. Separation of Concerns

Now there's a clear designated place for defining middleware instead of mixing it inside object initialization. This makes the code more organized and easier to understand and maintain.


2. Greater Expressiveness

Using the Middleware class, you can specify options like only and except in a declarative and clear way, instead of multiple method chains. The result: clean and clear code for any new developer joining the project.


3. More Scalable Structure

When dealing with complex or multi-layered Controllers, having a static middleware definition makes discovering and analyzing them easier, and helps Laravel organize their application internally.


Has the Old Style Stopped Working?

Not entirely — the old style using $this->middleware() inside __construct() still works as long as you haven't used the HasMiddleware interface. But the new style is officially recommended for new projects based on Laravel 11.


Conclusion

The transition to HasMiddleware in Laravel 11 isn't just a change in syntax, but a step towards clearer and more organized code that adheres to modern software engineering principles.


Laravel 11 continues to evolve towards simplicity and clarity — and as usual, leaves you the freedom to write elegant and easy-to-understand code.

Share Now ?
Let's chat