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 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 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 browser after all middlewares have been executed. The response can also be modified with middleware before it is sent to client or browser.
How to Create a Custom Middleware in Laravel?
The Laravel middlewares are basically code logic contained inside a PHP class. A Laravel custom middleware can be created with artisan command when run in a Laravel project directory. The command to create a middleware is as below:
php artisan make:middleware AuthenticateAPIRequest
After running the above command a middleware class AuthenticateAPIRequest will be created in directory app/Http/Middleware of Laravel project. Then we add the logic to validate requests for API token header as below:
- Store the API token in variable
$apiToken. This token can be stored in .env file of Laravel project and which then can be defined inconfig/app.phpfile or any separate file of your choice. - Fetch and store the authorization header in a variable
$authorizationHeaderfrom request. - Check if authorization is empty or if it does not match the token we have in project's .env file then throw JSON response error in an array with 401 error code.
- At the end return the current
$requestwhich will be passed to 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
app/Httpdirectory of Laravel project. - Open
Kernel.phpfile. - Find the
$middlewareAliasesarray and add the following alias to the array.
'authenticate_api_request' => \App\Http\Middleware\AuthenticateApiRequest::class,
How to Use Middleware in API Routes?
Now that our job of creating an API middleware and registering it with an alias is done, we can now use it in Laravel API routes. The usage of Laravel middleware will be something like in 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.