HTTP middleware provide a convenient mechanism for filtering HTTP requests entering our application. For example, Laravel includes a middleware that verifies the user of our application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/Middleware directory.
Defining Middleware
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware OldMiddleware
This command will place a new OldMiddleware class within our app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 20. Otherwise, we will redirect the users back to the "home" URI.
<?php
namespace App\Http\Middleware;
use Closure;
class OldMiddleware
{
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('age') <= 20) {
return redirect('home');
}
return $next($request);
}
}
As we can see, if the given age is less than or equal to 20, 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"), simply 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 our application. Each layer can examine the request and even reject it entirely.
Before / After Middleware
Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:
<?php
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// 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;
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
// Perform action
return $response;
}
}