middleware laravel 10 example
Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. All of these middleware are located in the app/Http/Middleware directory. To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware EnsureTokenIsValid
Of course, a middleware can perform tasks before or after passing the request deeper into the application.
Following middleware perform the task before request
class BeforeMiddleware
{
public function handle(Request $request, Closure $next): Response
{
if ($request->input('token') !== 'my-secret-token') {
return redirect('home');
}
return $next($request);
}
}
Following middleware perform the task After request
class AfterMiddleware
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
// Perform action
return $response;
}
}
Example:
public function handle(Request $request, Closure $next)
{
echo "Before Request".time();
$response = $next($request);
echo "After Request".time();
return $response;
}
In Laravel there are three levels where middleware can be applied
1.Register Global Middleware
If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
];
2.Assigning Middleware To Routes
use App\Http\Middleware\Authenticate;
Route::get('/profile', function () {
// ...
})->middleware(Authenticate::class);
For convenience, you may assign aliases to middleware in your application's app/Http/Kernel.php
protected $routeMiddleware = [
'red_if_nt_auth' => \App\Http\Middleware\RedirectIfNotAuthenticated::class,
];
then use
Route::get('/profile', function () {
// ...
})->middleware('red_if_nt_auth');
OR
Route::middleware(['auth', 'admin.task.check'])->group(function () {
Route::get('/todo', [TodoController::class, 'index']);
});
3. Middleware groups
File: app/Http/Kernel.php, in $middlewareGroups
These are groupings like web and api, usually applied in routes/web.php or routes/api.php.
So if your route is in web.php, it automatically has the web group middleware.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Terminable Middleware
The terminate method will automatically be called after the response is sent to the browser:
use Illuminate\Http\Response;
class TerminatingMiddleware
{
public function handle(Request $request, Closure $next): Response
{
return $next($request);
}
public function terminate(Request $request, Response $response): void
{
// ...
}
}
The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of routes or global middleware in the app/Http/Kernel.php file.
Check middleware of a specific route
php artisan route:list
SOME MIDDLEWERES:
TrustProxies : app/Http/Middleware/TrustProxies.php
TrustProxies is a Laravel middleware that deals with reverse proxies / load balancers.
It ensures correct client IP + HTTPS detection when your app is behind a proxy/load balancer.
use Illuminate\Http\Request;
Route::get('/check-ip', function (Request $request) {
return [
'request_ip' => $request->ip(),
'server_ip' => $_SERVER['REMOTE_ADDR'] ?? null,
'all_headers' => $request->headers->all(),
];
});
- Your TrustProxies middleware + Cloudflare combo is protecting you from header spoofing.
https://abc.org/check-ip -H "X-Forwarded-For: 203.0.113.55" -H "X-Forwarded-Proto: https" -H "X-Forwarded-Port: 443" - Request is HTTPS OR http
$request->secure() - Get IP
$request->ip()