Middleware
Introduction
Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. A variety of middleware are included in Laravel, including middleware for authentication and CSRF protection; however, all user-defined middleware are typically located in your application's app/Http/Middleware
directory.
Defining Middleware
To create a new middleware, use the make:middleware
Artisan command:
php artisan make:middleware EnsureTokenIsValid
This command will place a new EnsureTokenIsValid
class within your app/Http/Middleware
directory. In this middleware, we will only allow access to the route if the supplied token
input matches a specified value. Otherwise, we will redirect the users back to the /home
URI:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureTokenIsValid
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if ($request->input('token') !== 'my-secret-token') {
return redirect('/home');
}
return $next($request);
}
}
As you can see, if the given token
does not match our secret token, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), you should call the $next
callback with the $request
.
It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.
All middleware are resolved via the service container, so you may type-hint any dependencies you need within a middleware's constructor.
Middleware and Responses
Of course, a middleware can perform tasks before or after passing the request deeper into the application. For example, the following middleware would perform some task before the request is handled by the application:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class BeforeMiddleware
{
public function handle(Request $request, Closure $next): Response
{
// Perform action
return $next($request);
}
}
However, this middleware would perform its task after the request is handled by the application:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AfterMiddleware
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
// Perform action
return $response;
}
}
Registering Middleware
Global Middleware
If you want a middleware to run during every HTTP request to your application, you may append it to the global middleware stack in your application's bootstrap/app.php
file:
use App\Http\Middleware\EnsureTokenIsValid;
->withMiddleware(function (Middleware $middleware) {
$middleware->append(EnsureTokenIsValid::class);
})
The $middleware
object provided to the withMiddleware
closure is an instance of Illuminate\Foundation\Configuration\Middleware
and is responsible for managing the middleware assigned to your application's routes. The append
method adds the middleware to the end of the list of global middleware. If you would like to add a middleware to the beginning of the list, you should use the prepend
method.
Manually Managing Laravel's Default Global Middleware
If you would like to manage Laravel's global middleware stack manually, you may provide Laravel's default stack of global middleware to the use
method. Then, you may adjust the default middleware stack as necessary:
->withMiddleware(function (Middleware $middleware) {
$middleware->use([
// \Illuminate\Http\Middleware\TrustHosts::class,
\Illuminate\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
]);
})
Assigning Middleware to Routes
If you would like to assign middleware to specific routes, you may invoke the middleware
method when defining the route:
use App\Http\Middleware\EnsureTokenIsValid;
Route::get('/profile', function () {
// ...
})->middleware(EnsureTokenIsValid::class);
You may assign multiple middleware to the route by passing an array of middleware names to the middleware
method:
Route::get('/', function () {
// ...
})->middleware([First::class, Second::class]);
Excluding Middleware
When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware
method:
use App\Http\Middleware\EnsureTokenIsValid;
Route::middleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/', function () {
// ...
});
Route::get('/profile', function () {
// ...
})->withoutMiddleware([EnsureTokenIsValid::class]);
});
You may also exclude a given set of middleware from an entire group of route definitions:
use App\Http\Middleware\EnsureTokenIsValid;
Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/profile', function () {
// ...
});
});
The withoutMiddleware
method can only remove route middleware and does not apply to global middleware.
Middleware Groups
Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the appendToGroup
method within your application's bootstrap/app.php
file:
use App\Http\Middleware\First;
use App\Http\Middleware\Second;
->withMiddleware(function (Middleware $middleware) {
$middleware->appendToGroup('group-name', [
First::class,
Second::class,
]);
$middleware->prependToGroup('group-name', [
First::class,
Second::class,
]);
})
Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware:
Route::get('/', function () {
// ...
})->middleware('group-name');
Route::middleware(['group-name'])->group(function () {
// ...
});
Laravel's Default Middleware Groups
Laravel includes predefined web
and api
middleware groups that contain common middleware you may want to apply to your web and API routes. Remember, Laravel automatically applies these middleware groups to the corresponding routes/web.php
and routes/api.php
files:
The web Middleware Group |
---|
Illuminate\Cookie\Middleware\EncryptCookies |
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse |
Illuminate\Session\Middleware\StartSession |
Illuminate\View\Middleware\ShareErrorsFromSession |
Illuminate\Foundation\Http\Middleware\ValidateCsrfToken |
Illuminate\Routing\Middleware\SubstituteBindings |
The api Middleware Group |
---|
Illuminate\Routing\Middleware\SubstituteBindings |
If you would like to append or prepend middleware to these groups, you may use the web
and api
methods within your application's bootstrap/app.php
file. The web
and api
methods are convenient alternatives to the appendToGroup
method:
use App\Http\Middleware\EnsureTokenIsValid;
use App\Http\Middleware\EnsureUserIsSubscribed;
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
EnsureUserIsSubscribed::class,
]);
$middleware->api(prepend: [
EnsureTokenIsValid::class,
]);
})
You may even replace one of Laravel's default middleware group entries with a custom middleware of your own:
use App\Http\Middleware\StartCustomSession;
use Illuminate\Session\Middleware\StartSession;
$middleware->web(replace: [
StartSession::class => StartCustomSession::class,
]);
Or, you may remove a middleware entirely:
$middleware->web(remove: [
StartSession::class,
]);
Manually Managing Laravel's Default Middleware Groups
If you would like to manually manage all of the middleware within Laravel's default web
and api
middleware groups, you may redefine the groups entirely. The example below will define the web
and api
middleware groups with their default middleware, allowing you to customize them as necessary:
->withMiddleware(function (Middleware $middleware) {
$middleware->group('web', [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
]);
$middleware->group('api', [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
// 'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);
})
By default, the web
and api
middleware groups are automatically applied to your application's corresponding routes/web.php
and routes/api.php
files by the bootstrap/app.php
file.
Middleware Aliases
You may assign aliases to middleware in your application's bootstrap/app.php
file. Middleware aliases allow you to define a short alias for a given middleware class, which can be especially useful for middleware with long class names:
use App\Http\Middleware\EnsureUserIsSubscribed;
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'subscribed' => EnsureUserIsSubscribed::class
]);
})
Once the middleware alias has been defined in your application's bootstrap/app.php
file, you may use the alias when assigning the middleware to routes:
Route::get('/profile', function () {
// ...
})->middleware('subscribed');