DEV Community

Mohammed Samgan Khan
Mohammed Samgan Khan

Posted on • Originally published at codebysamgan.com

How to create and use a custom middleware in laravel 10

Creating a custom middleware in Laravel is a good way to add custom logic to the request-response cycle. Laravel itself use a number of middleware for specific tasks. Middleware can be used for tasks ranging from authentication, authorization, logging to tasks like adding data to request etc. etc. etc..

Below is a step-by-step guide showing how to create a middleware in laravel.

Create the Middleware

To create a middleware use the following command in your terminal.

php artisan make:middleware CustomMiddleware
Enter fullscreen mode Exit fullscreen mode

This command will create a new middleware file named CustomMiddleware.php in the app/Http/Middleware directory.

The file create will look something like this

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CustomMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Closure(Request): (Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

Update the Middleware

The entire logic goes in the handle function. You can modify the request, perform checks, and take actions based on the conditions you define.

Register the Middleware

To make your middleware functional, you need to register it in Laravel's middleware stack. Open the app/Http/Kernel.php file and locate the $middleware array. Add an entry for your custom middleware class. Make sure you use the complete file path of the middleware.

protected $middleware = [
    // Other middleware entries
    \App\Http\Middleware\CustomMiddleware::class,
];
Enter fullscreen mode Exit fullscreen mode

Note: if you will add the entry to $middleware array, your middleware will be applied on all the request through out the application. Including web and api. Add to $middlewareGroups.web for web requests only and $middlewareGroups.api for api requests only.

Applying the Middleware

Now this middleware can be applied to routes or route groups.

Route::get('/example', 'ExampleController@index')->middleware('custom')->name('example');
Enter fullscreen mode Exit fullscreen mode

In this example, the custom middleware will be applied to the example route.

For more details you can always refer to the Laravel documentation for the most up-to-date information and additional middleware options. Laravel Middleware Documentation

Top comments (0)