Creating a custom middleware in Laravel is a good way to add custom logic to the request-response cycle. Laravel itself uses a number of middleware for specific tasks. Middleware can be used for tasks ranging from authentication, authorization, and logging to tasks like adding data to requests, 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

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

The file created 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);
    }
}

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,
];
Note: If you add the entry to the $middleware array, your middleware will be applied to all the requests throughout 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');

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