Skip to content

Middleware

Middleware is a powerful concept in web development that allows you to modify and filter HTTP requests and responses. In this guide, we'll show you how to create and use middleware in a PHP application.

What is Middleware?

Middleware is a layer of software that sits between a client and a server. It is responsible for handling HTTP requests and responses and can modify, filter or redirect them as necessary. Middleware can be used to implement features like authentication, rate limiting, logging, caching, and more.

Middleware operates on the principle of "chain of responsibility", where each middleware component in the chain performs a specific task and passes the request to the next middleware in the chain. The last middleware in the chain returns the final response to the client.

Creating Middleware

In PHP, middleware is implemented as a class that has a single method named handle(). This method takes two arguments: the HTTP request and a closure that represents the next middleware in the chain.

Here's an example of a simple middleware class that checks if a user is logged in:

<?php

namespace App\Middlewares;

class AuthenticationMiddleware
{
    public static function handle()
    {
        if (!isset($_SESSION['USER'])) {
            redirect('login');
            exit();
        }
    }
}

In this example, we have created a class called AuthenticationMiddleware that checks if the $_SESSION['USER'] variable is set. If it is not set, the middleware redirects the user to the login page.

Using Middleware

You can apply middleware to routes using the middleware method:

Route::get('/dashboard', function () {   
    // ...
}, AuthenticationMiddleware::class);