Introduction
Middleware acts like a gatekeeper that checks requests before they reach your app. It helps keep your app safe and organized by filtering requests.
Middleware acts like a gatekeeper that checks requests before they reach your app. It helps keep your app safe and organized by filtering requests.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckSomething { public function handle(Request $request, Closure $next) { // Check or modify the request here if (/* some condition */) { return redirect('somewhere'); } return $next($request); } }
handle method that gets the request and a next function.$next($request) to let the request continue to the app.<?php
public function handle(Request $request, Closure $next)
{
if (!$request->user()) {
return redirect('login');
}
return $next($request);
}<?php
public function handle(Request $request, Closure $next)
{
if ($request->header('X-Blocked')) {
abort(403, 'Access denied');
}
return $next($request);
}This middleware checks if the user is under 18 years old. If yes, it redirects them to a 'no-access' page. Otherwise, it lets the request continue.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckAge { public function handle(Request $request, Closure $next) { if ($request->input('age') < 18) { return redirect('no-access'); } return $next($request); } }
Always call $next($request) to pass the request along.
Middleware can stop requests early by returning a response like redirect or error.
Middleware filters requests to protect and control access.
It checks or changes requests before they reach your app.
You use middleware to keep your app safe and organized.
public function handle($request, Closure $next) {
if (!$request->hasHeader('token')) {
return response('Unauthorized', 401);
}
return $next($request);
}public function handle($request, Closure $next) {
if ($request->header('X-API-KEY') == null) {
$next($request);
}
return response('Forbidden', 403);
}Pass the test and this pattern moves unknown