Laravel HasMiddleware Interface

LaravelWeb Development

Laravel makes it easy to assign middleware directly to your Controller classes. To do this, your controller should implement the HasMiddleware interface.

Once you implement HasMiddleware, your controller needs to define a static middleware method. Through this method, you simply return an array containing all the middleware you want applied to the controller’s actions.

As an example, I’ve created a controller called PostController, which contains two methods: index and view. In both, I just returned some sample text, but you’re free to add whatever logic suits your application.

To expose these controller actions, we’ll set up two routes:

Route::get('/post', [\App\Http\Controllers\PostController::class, 'index']);
Route::get('/post/view', [\App\Http\Controllers\PostController::class, 'view']);

Next, let’s add a static middleware method to the controller:

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            'auth'
        ];
    }

    public function index(): string {
        return 'Post Page';
    }

    public function view(): string {
        return "This is Post view page";
    }
}

Here, you specify any middleware you wish to enforce on this controller. In my example, I’m applying Laravel’s built-in auth middleware. This means that if a user isn’t logged in, any attempt to access the methods in PostController will send them to the login page.

But what if you only want middleware to run on the index method (and not on view)? Laravel lets you specify particular actions using the only option. Here’s how:

public static function middleware(): array
{
    return [
        new Middleware('auth', only: ['index']),
    ];
}

With this structure, the auth middleware will only be triggered for the index action, ensuring users are authenticated before accessing it. If they’re not, they’ll be redirected to the login page.

Conversely, you might want to exclude middleware from specific actions. For example:

public static function middleware(): array
{
    return [
        new Middleware('auth', only: ['index']),
        new Middleware('verified', except: ['store']),
    ];
}

Here, the verified middleware will apply to every method except store.

Thanks for checking out this article!