How to create global middleware in Laravel

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

Introduction

Laravel is a popular PHP framework known for its elegant syntax and tools that facilitate rapid web application development. One such tool is the middleware mechanism that allows you to filter HTTP requests entering your application. In this tutorial, we will discuss what middleware is and provide step-by-step guidance on how to create global middleware in Laravel.

Understanding Middleware

In Laravel, middleware provides a convenient way to inspect and filter HTTP requests before they reach your application. It can be used to perform various tasks, such as authenticating users, logging requests, or even preventing access to certain resources.

Creating a Middleware in Laravel

To create a middleware, you can use the artisan command line tool provided by Laravel. Run the following command:

php artisan make:middleware EnsureTokenIsValid

This command creates a middleware class named EnsureTokenIsValid within the app/Http/Middleware directory.

Middleware Class Structure

<?php

namespace App\Http\Middleware;

use Closure;

class EnsureTokenIsValid
{
    public function handle($request, Closure $next)
    {
        // Perform action before the request is handled by the application

        return $next($request);
    }
}

In this class, the handle method is where you will place your middleware logic.

Registering Global Middleware

To register middleware globally, add it to the middleware array in your app/Http/Kernel.php file:

protected $middleware = [
    // Other middleware
    \App\Http\Middleware\EnsureTokenIsValid::class,
];

Once registered, the middleware will be executed on every HTTP request to your application.

Implementing Middleware Logic

public function handle($request, Closure $next)
{
    if ($request->input('token') !== 'secret') {
        return response('Unauthorized.', 401);
    }

    return $next($request);
}

In the above example, the middleware checks if the input token matches a pre-defined string, ‘secret’. If not, it returns an unauthorized response.

Testing Middleware

Once your middleware is implemented, you should test it to ensure it functions as expected. Here is an example route for testing:

Route::get('/test', function () {
    return 'Token is valid.';
});

If you access this route without the proper token, you should see a 401 unauthorized error.

Passing Data Through Middleware

You can pass data from middleware to your application using the request’s attributes. For instance:

public function handle($request, Closure $next)
{
    $request->attributes->add(['token_valid' => true]);
    return $next($request);
}

To access the attribute later in your application:

$tokenValid = $request->attributes->get('token_valid');

Terminable Middleware

Laravel also supports middleware that runs after the response is sent to the browser, known as terminable middleware. To make your middleware terminable, simply define a terminate method:

public function terminate($request, $response)
{
    // This will be called after the response is sent
}

Global Middleware Best Practices

When you’re creating global middleware, don’t forget to be cautious, as it will affect every request to your application. Make sure that the operations are lightweight and essential for every request.

Conclusion

In summary, middleware acts as a powerful filter for HTTP requests in Laravel. Creating and registering global middleware is straightforward with artisan commands and simple modifications to the Kernel. By following the steps outlined in this tutorial, you will be able to leverage middleware to execute logic on every request, ensuring a centralized handling mechanism for crucial tasks.