Create a Laravel Middleware (Register & Use with Example)
Laravel middleware is like a bridge between requests and responses in a Laravel application. Learn in this post how to create and register a middleware in a Laravel application.

With Laravel middleware, it is possible to inspect or modify HTTP requests before they reach the controller methods and serve the proper response to web browsers based on these requests. In simple words, a Laravel middleware is used to filter requests and responses in a Laravel application. In this post, we are going to make a Laravel middleware and we will validate requests for an API token with this middleware. This middleware works as a Laravel auth middleware by validating API requests using the authorization header.
How Does a Laravel Middleware Work?
When a user hits a URL of a Laravel application or sends a request to Laravel application, the requests is sent to HTTP kernel which defines list of various global and route specific middlewares. Each Laravel middleware is then run in sequence to validate or modify the request. The request continues if the middleware passes and then finally the response is sent to the browser after all middlewares have been executed. The response can also be modified with middleware before it is sent to the client or browser.
How to Create a Custom Middleware in Laravel?
The Laravel middlewares are basically code logics contained inside a PHP class. A Laravel custom middleware can be created with an artisan command by running it in a Laravel project directory. The command to create a middleware is as follows:
php artisan make:middleware AuthenticateAPIRequest
After running the above command, a middleware class AuthenticateAPIRequest will be created in the directory app/Http/Middleware of the Laravel project. Then we add the logic to validate requests for the API token header as below:
- Store the API token in a variable
$apiToken. This token can be stored in the.envfile of the Laravel project, and then can be defined in theconfig/app.phpfile or any separate file of your choice. - Fetch and store the authorization header in a variable
$authorizationHeaderfrom the request. - Check if authorization is empty or if it does not match the token we have in the project's
.envfile, then throw a JSON response error in an array with a 401 error code. - At the end, return the current
$request, which will be passed to the next middleware in sequence.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthenticateApiRequest
{
/**
* Handle an incoming request.
*
* @param Closure(Request): (Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$apiToken = config('app.api_token'); // Retrieve this from your config file
$authorizationHeader = $request->header('Authorization');
if (empty($authorizationHeader) || $authorizationHeader !== sprintf('Bearer %s', $apiToken)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
How to Register a Laravel Middleware?
Now that we have our logic implemented in our API middleware class, we need to register it with an alias to use in our routes. To register Laravel middleware, follow these steps:
- Navigate to the
app/Httpdirectory of the Laravel project. - Open the
Kernel.phpfile. - Find the
$middlewareAliasesarray and add the following alias to the array.
'authenticate_api_request' => \App\Http\Middleware\AuthenticateApiRequest::class,
How to Use a Middleware in API Routes?
Now that our job of creating an API middleware and registering it with an alias is done, we can use it in Laravel API routes. The usage of Laravel middleware will be something like in the code snippet below:
Route::middleware(['authenticate_api_request'])->group(function(){
// Your API routes go here
});We demonstrated how to create a Laravel middleware and validate requests for authorization headers. This middleware can serve the purpose of route middleware or api middleware for API requests by validating the authorization header.