Middleware in Laravel 12

Middleware s in laravel

What is Middleware in Laravel?

Middleware in Laravel is like a security guard or checkpoint that sits between your HTTP request and your application's response.
Whenever a request hits your application, it passes through a series of middleware layers before reaching the controller logic.

Think of middleware as filters:

  • You can allow or block requests

  • You can modify requests or responses

  • You can check authentication or roles before letting the user move forward

In simple words, middleware controls access and flow inside your Laravel app.


Why Middleware is Important

Middleware plays an important role in almost every Laravel project:

  • Security : Blocks unauthorized access to protected routes

  • Authentication & Authorization : Checks if a user is logged in or has certain roles

  • Request Filtering : Modify or validate data before reaching your controller

  • Clean Code Structure : Keeps controllers simple and focused on business logic


Types of Middleware in Laravel

Laravel 12 offers different types of middleware. Each serves a specific purpose:

  1. Global Middleware

    • Runs on every HTTP request coming into your application

    • Example: Checking if the app is in maintenance mode

    • Registered in: bootstrap/app.php file using the withMiddleware() method

  2. Route Middleware

    • Applied only to specific routes or route groups

    • Example: Authentication middleware

      • Registered in: bootstrap/app.php file using the withMiddleware() method
  3. Middleware Groups

    • A set of middleware combined under one group

    • Example: web group for web routes, api group for API routes

    • Useful when you want to apply multiple middleware on a group of routes


Creating a Custom Middleware in Laravel 12

Let’s go step-by-step and build a simple custom middleware.

Step 1: Create Middleware

Use Artisan command to generate a middleware file:

php artisan make:middleware AdminAuth
This will create:
app/Http/Middleware/AdminAuth.php

Step 2: Add Logic in Middleware

Open AdminAuth.php and add your logic:

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */

    public function handle(Request $request, Closure $next): Response
    {
        if (!auth()->guard('admin')->check()) {
            toastr()->error('Please login first');
            return redirect()->route('admin.login');
        }
        return $next($request);
    }
} 

This middleware will redirect users who are not Admin.


Step 3: Register the Middleware

Go to bootstrap/app.php and register your middleware with withMiddleware() method

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )

    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'adminauth' => \App\Http\Middleware\AdminAuth::class,
        ]);
    })

    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Step 4: Apply Middleware to Routes

Now use this middleware in your route:

 Route::prefix('admin/')->middleware('adminauth')->group(function () {
Route::get('dashboard', [DashboardController::class, 'dashboard'])->name('admin.dashboard');
});

Whenever a user visits /dashboard, the middleware will run first.


How to Use Built-in Middleware

Laravel includes several built-in middleware such as:

  • auth → ensures user is logged in

  • guest → ensures user is logged out

  • verified → checks if email is verified

  • throttle → rate-limits requests

  • signed → validates signed URLs

Example:

Route::get('/profile', function () {
    return view('profile');
})->middleware('auth');

This route will only be accessible if the user is authenticated.


Middleware Location in Laravel 12 Project

Middleware files live inside:
app/Http/Middleware

You can also see middleware groups and route middleware defined in:
bootstrap/app.php

This is where Laravel decides which middleware run for which routes.


Common Use Cases of Middleware

Here are a few practical examples of using middleware in real projects:

  • Authentication checks before accessing private pages

  • Role-based access (admin vs user)

  • Block inactive or banned users

  • Log requests for analytics

  • Modify headers or responses for security (CORS, Content-Type)


❓ FAQs about Laravel Middleware

These FAQs cover extra keywords you provided which don’t fit naturally in the main content:

Q1. How to register middleware in Laravel 12?
Go to bootstrap/app.php and add it into $withmiddleware(). Use php artisan make:middleware to create first.

Q2. How to call middleware in a Laravel controller?
You can use it in the controller’s constructor:

$this->middleware('auth');

Q3. What is the difference between auth and guest middleware in Laravel?

  • auth ensures user is logged in

  • guest ensures user is logged out

Q4. How to redirect in middleware in Laravel?
You can return redirect('/login') from inside the handle() method.

Q5. How to use middleware in API routes in Laravel?
You can apply them on API routes in routes/api.php using ->middleware('auth:sanctum') or any custom API middleware.

Q6. How to add middleware in Laravel 12?
Create it with Artisan → Register in bootstrap/app → Use it in routes or controllers.

Q8. How to use auth middleware in Laravel API?
Use Laravel Sanctum or Passport and then add ->middleware('auth:sanctum') on your API routes.


Final Thoughts

Middleware is one of the most powerful yet simple features of Laravel. It helps keep your app secure, clean, and organized by filtering requests.

Now that you understand what middleware is, how it works, and how to create your own, you’re ready to apply it in your real projects.