How to create Custom Middlewares in Laravel

Posted on August 24th, 2024

Creating custom middleware in Laravel lets you manage HTTP requests efficiently, adding a layer of control before they hit your application or before responses are sent out. Here are some practical ways to use middleware:

  • User Authentication: Use middleware to check if a user is logged in before they access certain parts of your site, like an admin dashboard. If they’re not logged in, you can redirect them to a login page.
  • API Request Logging: Log details of every API request, such as the URL and response time. This helps with monitoring and troubleshooting without cluttering your main application logic.
  • IP Address Restrictions: Restrict access to certain areas based on the user’s IP address. For example, only allow requests from specific IPs for sensitive routes.
  • Rate Limiting: Prevent abuse by limiting how many requests a user can make in a set period. Middleware can track request counts and block excessive usage.
  • Content Modification: Add headers to responses or modify request data across your app, like setting security headers or adjusting input data.
  • User Locale Setting: Automatically set the language for users based on their preferences or browser settings, so they see content in their preferred language.

In this guide, we’ll show you how to create and apply custom middleware in Laravel. Whether it’s for authentication, logging, or any of these use cases, middleware helps you manage your application’s behavior and enhance functionality.

Step 1: Generate the Middleware

The first step in creating custom middleware is generating a new class using Artisan. This class will contain the logic for your custom middleware.

Open your terminal: Access the command line interface where you run Artisan commands.

Run the Artisan command: Enter the following command to generate a new middleware class:

php artisan make:middleware CustomMiddleware

This command creates a new file CustomMiddleware.php in the app/Http/Middleware directory.

Verify the file creation: Navigate to app/Http/Middleware and open CustomMiddleware.php to define your middleware logic.

Step 2: Define the Middleware Logic

Next, you must define the logic your custom middleware will execute. Open app/Http/Middleware/CustomMiddleware.php and implement the handle method.

Here’s an example of a middleware that checks if a user is accessing the application from a specific IP address:

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;

class CustomMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        // Define the IP address to check
        $allowedIp = '123.456.789.000';
        
        // Check if the request's IP address matches the allowed IP
        if ($request->ip() !== $allowedIp) {
            // Optionally, redirect to an error page or return a specific response
            return response('Unauthorized.', 401);
        }
        
        // Continue to the next middleware or request handler
        return $next($request);
    }
}
?>

The handle method receives two parameters: $request (the incoming request) and $next (a closure to pass the request to the next middleware). In this example, the middleware checks if the request’s IP address matches a specific IP address. If not, it returns a 401 Unauthorized response. Otherwise, the request is passed on to the next middleware or controller.

Step 3: Register the Middleware

Once you’ve defined your middleware, you need to register it so that Laravel knows about it and can apply it to your routes.

Open app/Http/Kernel.php: This file contains the middleware registration for your application.

Register the middleware: Add your custom middleware to the $middleware array for global middleware or $routeMiddleware array for route-specific middleware.

Here’s how to add it to the $routeMiddleware array:

protected $routeMiddleware = [
    // Other middleware
    'custom' => \App\Http\Middleware\CustomMiddleware::class,
];

$routeMiddleware Array: This array maps middleware aliases to their corresponding classes. Adding 'custom' => \App\Http\Middleware\CustomMiddleware::class allows you to use the custom alias when applying middleware to routes.

Step 4: Apply the Middleware to Routes

With your middleware registered, you can now apply it to your routes or route groups. There are several ways to do this:

Apply to a single route: use Illuminate\Support\Facades\Route;

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

middleware Method: This method applies the custom middleware to the specified route.

Apply to a route group: If you want to apply a middleware on multiple routes, This method is very effective. First, Include the Route facade and follow the syntax given below.

use Illuminate\Support\Facades\Route;

Route::middleware(['custom'])->group(function () {
    Route::get('/example1', function () {
        // Your route logic here
    });
    Route::get('/example2', function () {
        // Your route logic here
    });
});

So, This is how you can use middlewares to limit access to the system using custom midd.

Usage Benefits

  • Custom Logic: Middleware allows you to inject custom logic into the request lifecycle, providing flexibility for various tasks such as authentication, logging, and request manipulation.
  • Reusability: Middleware can be reused across multiple routes or controllers, ensuring consistent behavior and reducing code duplication.
  • Separation of Concerns: By isolating middleware logic from controllers, you keep your codebase clean and maintainable, with middleware focusing on specific concerns.

Conclusion

Building custom middleware in Laravel increases your ability to handle HTTP requests with logic specific to your application’s needs. Following these steps, you can define, register, and apply middleware effectively, making your application more robust and flexible. Custom middleware allows you to enforce rules, handle requests uniquely, and keep your application’s logic organized and maintainable.

Leave a Reply