Middleware are one of the most important parts of any good application. Described often as a "software glue" , It's what stands between the web and our app intercepting every HTTP request.
Konstantinos Kazazis
Software DeveloperNow middleware is a broad term that refers to any kind of software sitting in between two systems. They can ensure the exchange of data even if the systems are isolated. Let's go over some examples of middleware in the world of computing:
Everything sounds good so far but what about Laravel? How would someone define and use middleware?
We would have to start from the following folder:
app/http/middleware
and as always, artisan has our back:
php artisan make:middleware MyMiddleware
Next step would be to define the middleware function itself. We could execute code before or after passing the incoming request to the application like so:
class MyMiddleware
{
public function handle(Request $request, Closure $next): Response
{
// Perform action before request
// ---- your code ----
// return $next($request);
// ---- or ----
// Perform action after
// ---- your code ----
//$response = $next($request);
//return $response;
}
}
After creating our middleware through artisan and writing the functions its time to decide weather we want the code to run in every request or on specific routes.
In case we want to run the middleware for every request we need to use our global middleware stack located in bootstrap/app.php like so:
use App\Http\Middleware\MyMiddleware;
->withMiddleware(function (Middleware $middleware): void {
$middleware->append(MyMiddleware::class);
})
Otherwise we can even specify the middleware per route in web.php:
use App\Http\Middleware\EnsureTokenIsValid;
Route::get('/profile', function () {
// ...
})->middleware(MyMiddleware::class);