How to Define Middleware in Laravel

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Middleware in Laravel provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. This tutorial will guide you through the basics of creating and using middleware in Laravel. We will begin with simple examples and gradually move to more advanced use cases.

Understanding Middleware

Middleware in Laravel is used to modify the request before it reaches the controller and the response before it’s sent back to the client. It can be used for logging, authentication, caching, etc.

Creating Middleware

To create middleware in Laravel, use the make:middleware Artisan command:

php artisan make:middleware CheckAge

This command will create a new CheckAge middleware within the app\Http\Middleware directory.

Defining Middleware Logic

Edit the generated middleware to implement your logic:

public function handle($request, Closure $next)
{
    if ($request->age 
    return $next($request);
}

Registering Middleware

Register middleware in the app\Http\Kernel.php file. You can register as a global middleware, route middleware, or group middleware.

Global Middleware

protected $middleware = [
    \App\Http\Middleware\CheckAge::class,
];

Route Middleware

protected $routeMiddleware = [
    'age' => \App\Http\Middleware\CheckAge::class,
];

To use route middleware, assign it to a route:

Route::get('profile', 'ProfileController@show')->middleware('age');

Parameters in Middleware

Middleware can also receive parameters. Let’s modify the CheckAge middleware to accept a minimum age parameter:

public function handle($request, Closure $next, $age)
{
    if ($request->age < $age) {
        return redirect('home');
    }
    return $next($request);
}

To pass a parameter to route middleware:

Route::get('profile', 'ProfileController@show')->middleware('age:18');

Middleware Groups

Laravel includes middleware groups that allow you to combine several middleware and assign them to a route or route group:

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    ...,
    \App\Http\Middleware\VerifyCsrfToken::class,
],

Apply a middleware group to routes:

Route::group(['middleware' => ['web']], function () {
    Route::get('/', function () {
        // Uses 'web' middleware group...
    });
});

Middleware Priorities

Set the order of global middleware by listing them in the $middlewarePriority array in the Kernel class:

protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \App\Http\Middleware\Authenticate::class,
    ...,
];

Terminable Middleware

Laravel allows middleware to perform tasks after the response has been sent to the browser:

public function terminate($request, $response)
{
    // Perform some action
}

The terminate method is only called if your middleware implements the Terminable interface.

Testing Middleware

Test your middleware by defining tests that make HTTP requests to your application and asserting the expected behavior:

public function testMiddleware()
{
    $response = $this->get('profile');
    $response->assertStatus(302);
}

Advanced Middleware Usage

For more complex applications, middleware can be used in advanced scenarios, such as rate limiting, CORS, or transforming the response data into a specific format.

Using Middleware to Transform Responses

Middleware can modify responses just before they are sent to the client:

public function handle($request, Closure $next)
{
    $response = $next($request);
    // Modify the response here
    return $response;
}

Dynamic Middleware Assignment

Laravel allows assigning middleware dynamically from a controller’s constructor or method:

public function __construct()
{
    $this->middleware('age', ['only' => ['show']]);
}

Conclusion

In this guide, we have explored the different ways to define, register, and implement middleware in Laravel, from basic to advanced use cases. With this knowledge, you can customize the request and response cycle to suit your application’s needs effectively.