Laravel Middleware

What is Middleware?

In Laravel, Middleware acts as a bridge between the request and the response.

Every HTTP request entering your Laravel app passes through middleware before reaching controllers/routes.

For example:

  • Check if the user is authenticated.
  • Verify if a request has a valid API key.
  • Log every request.
  • Restrict routes based on roles.

Why Use Middleware?

Middleware helps you to:

  1. Secure routes – ensure only logged-in users can access.
  2. Modify requests/responses – add headers, manipulate data.
  3. Global behaviors – logging, CORS, trimming strings, etc.
  4. Role-based permissions – Admin, User, Guest.
  5. Reusable logic – write once, apply anywhere.

Without middleware, you would have to repeat the same code in every controller – ❌ not good for maintainability.


Defining a Middleware

Use Artisan to create middleware:

php artisan make:middleware EnsureTokenIsValid

This creates app/Http/Middleware/EnsureTokenIsValid.php.


Add Conditions (app/Http/Middleware/EnsureTokenIsValid.php)

class EnsureTokenIsValid
{
    public function handle(Request $request, Closure $next): Response
    {
        if($request->token !== 'my-secret-token'){
            abort(403, 'Unauthorized action.');
        }
        return $next($request);
    }
}
  • Check a condition if given request token is my-secret-token condition true go to net step or It move 403 Unauthorized


Register Middleware (bootstrap/app.php)

use App\Http\Middleware\EnsureTokenIsValid;
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'check.token' => EnsureTokenIsValid::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();


Add middleware to route (routes/web.php)

Route::get('/welcome', function(){
    return "welcome";
})->middleware('check.token');


Output with my-secret-token:


Output without my-secret-token:


Types of Middleware in Laravel 12

Laravel provides different kinds of middleware:

a) Global Middleware

  • Applied to every HTTP request automatically.
  • Example: TrimStrings, ConvertEmptyStringsToNull.
  • Useful for logging, CORS, etc.
// bootstrap/app.php
->withMiddleware(function ($middleware) {
  $middleware->append(\App\Http\Middleware\CheckForMaintenanceMode::class);
});

b) Route Middleware (Alias)

  • Applied only on specific routes.
  • You assign an alias for easy usage.
// bootstrap/app.php
->withMiddleware(function ($middleware) {
    $middleware->alias([
        'check.token' => \App\Http\Middleware\EnsureTokenIsValid::class,
    ]);
});

// routes/web.php
Route::get('/dashboard', function () {
    return "Dashboard";
})->middleware('check.token');

c) Middleware Groups

  • Bundle multiple middleware into one group.
  • Example: web, api groups already exist in Laravel.
// bootstrap/app.php
->withMiddleware(function ($middleware) {
  $middleware->web(append: [\App\Http\Middleware\ExampleWebMiddleware::class]);
  $middleware->api(prepend: [\App\Http\Middleware\ExampleApiMiddleware::class]);
});

// routes/web.php
Route::middleware('web')->group(function () {
  Route::get('/profile', fn() => "Profile Page");
});

d) Parameterized Middleware

  • Pass arguments to middleware.
// Middleware
public function handle($request, Closure $next, $role)
{
  if (! $request->user() || $request->user()->role !== $role) {
    return redirect('/unauthorized');
  }
  return $next($request);
}

// Route
Route::get('/admin', fn() => "Admin Panel")->middleware('check.role:admin');

e) Terminable Middleware

  • Runs after the response is sent to the browser.
  • Example: logging response time.
public function handle($request, Closure $next)
{
  return $next($request);
}

public function terminate($request, $response)
{
  \Log::info("Request ended at ".now());
}

4. How Middleware Works in Laravel 12

Unlike Laravel 10/11 where you had Kernel.php, in Laravel 12 middleware is configured inside bootstrap/app.php:

return Application::configure(basePath: dirname(__DIR__))
  ->withMiddleware(function ($middleware) {
    // Register global middleware
    $middleware->append(\App\Http\Middleware\TrimStrings::class);

    // Register aliases
    $middleware->alias([
      'auth.check' => \App\Http\Middleware\AuthCheck::class,
    ]);

    // Add to groups
    $middleware->web(append: [\App\Http\Middleware\ExampleWebMiddleware::class]);

    // Set priority order
    $middleware->priority([
      \App\Http\Middleware\ImportantFirst::class,
      \App\Http\Middleware\Second::class,
    ]);
  })
  ->withRouting(
    web: __DIR__.'/../routes/web.php',
    api: __DIR__.'/../routes/api.php',
  )
  ->create();

5. Where to Use Middleware?

  • Authentication → Check if user is logged in before accessing /dashboard.
  • Role-based Access → Allow only admins to /admin.
  • API Token Validation → Validate API keys for requests.
  • CORS & Headers → Modify request/response headers.
  • Logging → Store logs of every request.
  • Localization → Set app language dynamically.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.