Blog

How to create Middleware in Laravel with Examples

Laravel

How to create Middleware in Laravel with Examples

Middleware in Laravel

Middleware in Laravel is a powerful mechanism that allows you to filter HTTP requests entering your application. It provides a convenient way to perform actions before or after the request enters the application’s core logic. In this article, we will learn about the Laravel middleware concepts, usage, and creating examples to illustrate its practical application.

1. Introduction

Middleware acts as a bridge between the incoming HTTP request and the application’s core logic. It allows you to perform various tasks such as authentication, logging, modifying requests, and more. Understanding how to create and use middleware is fundamental for building robust and secure Laravel applications.

2. What is Laravel Middleware

Middleware in Laravel follows the Chain of Responsibility pattern. Each middleware component in the chain can either handle the request or pass it along to the next middleware. This chain of middleware provides a flexible way to filter and modify requests entering your application.

3. Creating Your First Middleware

Let’s start by creating a simple middleware that logs information about the incoming request. Use the following Artisan command to generate a new middleware:

php artisan make:middleware LogHttpRequest

This command creates a new middleware class named LogHttpRequest in the app/Http/Middleware directory.

// app/Http/Middleware/LogHttpRequest.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogHttpRequest
{
    public function handle($request, Closure $next)
    {
        // Log information about the incoming request
        Log::info("Request received. Path: {$request->path()}, Method: {$request->method()}");

        return $next($request);
    }
}

4. Middleware Parameters

Middleware can accept parameters, allowing you to make them more dynamic and reusable. Parameters are passed to the middleware constructor. We’ll explore how to use parameters in middleware by creating an example that adds a custom header to the HTTP response.

// app/Http/Middleware/AddCustomHeader.php

namespace App\Http\Middleware;

use Closure;

class AddCustomHeader
{
    protected $headerValue;

    public function __construct($headerValue)
    {
        $this->headerValue = $headerValue;
    }

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Add a custom header to the HTTP response
        $response->headers->set('X-Custom-Header', $this->headerValue);

        return $response;
    }
}

5. Global Middleware vs. Route Middleware

Laravel supports two types of middleware: global middleware and route middleware. Global middleware runs on every HTTP request, while route middleware is assigned to specific routes or groups of routes. We’ll discuss when to use each type and how to implement them.

6. Middleware Groups

Middleware groups allow you to group several middleware under a single key. This is useful when you want to apply multiple middleware to a group of routes. We’ll see how to define middleware groups and apply them to routes.

7. Built-in Laravel Middleware

Laravel comes with several built-in middleware that cover common scenarios like authentication, CSRF protection, and maintenance mode. We’ll explore these built-in middleware and understand how they contribute to the security and functionality of your application.

8. Creating Custom Middleware Examples

Authentication Middleware

We’ll create a custom authentication middleware that checks if a user is logged in. This middleware will protect routes that require authentication.

// app/Http/Middleware/AuthenticationMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AuthenticationMiddleware
{
    public function handle($request, Closure $next)
    {
        // Check if the user is authenticated
        if (Auth::check()) {
            return $next($request);
        }

        // Redirect to the login page if not authenticated
        return redirect('/login')->with('error', 'Unauthorized. Please log in.');
    }
}

Logging Middleware

Building on our initial example, we’ll enhance the logging middleware to log additional information such as the route being accessed and the response status.

// app/Http/Middleware/LoggingEnhancedMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LoggingEnhancedMiddleware
{
    public function handle($request, Closure $next)
    {
        // Log additional information
        Log::info("Request handled. Route: {$request->route()->getName()}, Response Status: {$next($request)->status()}");

        return $next($request);
    }
}

Maintenance Mode Middleware

Create a middleware that checks if the application is in maintenance mode. If the application is in maintenance mode, the middleware will display a custom maintenance page.

// app/Http/Middleware/MaintenanceModeMiddleware.php

namespace App\Http\Middleware;

use Closure;

class MaintenanceModeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Check if the application is in maintenance mode
        if (app()->isDownForMaintenance()) {
            // Display a custom maintenance page
            return response()->view('maintenance');
        }

        return $next($request);
    }
}

9. Registering Middleware

After creating middleware, you need to register it with Laravel. We’ll cover the various ways to register middleware, including the kernel property in the Http/Kernel.php file, global middleware in the AppServiceProvider, and using middleware groups.

// app/Http/Kernel.php

//a. Global Middleware:
protected $middleware = [
    // Other middleware...
    \App\Http\Middleware\LogHttpRequest::class,
];

// b. Route Middleware:
protected $routeMiddleware = [
    // Other route middleware...
    'auth' => \App\Http\Middleware\AuthenticationMiddleware::class,
    'logEnhanced' => \App\Http\Middleware\LoggingEnhancedMiddleware::class,
    'maintenance' => \App\Http\Middleware\MaintenanceModeMiddleware::class,
];

10. Apply the Middleware to Routes or Controllers:

Now that your custom middleware is registered, you can apply it to specific routes or controllers. You can do this in the web.php routes file or in the controller constructor.

a. Applying to Routes:

Route::get('/example', function () { // Your route logic here })->middleware('custom');

b. Applying to Controllers:

use App\Http\Controllers\ExampleController; Route::get('/example', [ExampleController::class, 'index'])->middleware('custom');

5. Customize Middleware Parameters (Optional):

If your middleware requires additional parameters, you can pass them when applying the middleware. Modify the middleware registration in the Kernel.php file and update the handle method accordingly:

// In Kernel.php protected $routeMiddleware = [ // Other middleware... 'custom' => \App\Http\Middleware\CustomMiddleware::class, ]; // In CustomMiddleware.php public function handle($request, Closure $next, $parameter) { // Middleware logic with parameter // Continue the request lifecycle return $next($request); }

When applying the middleware, pass the parameter like this:

Route::get('/example', function () { // Your route logic here })->middleware('custom:your_parameter');

10. Conclusion

Middleware is a crucial aspect of Laravel development, providing a flexible and efficient way to filter HTTP requests. In this comprehensive guide, we explored the fundamentals of middleware, created custom middleware with practical examples, and discussed how to register and use them in Laravel applications. As you continue your Laravel journey, mastering middleware will empower you to build more secure, modular, and efficient web applications. Happy coding!

Leave your thought here