Imagine visiting a modern office building. Before you can take the elevator to the fifth floor, a friendly security guard at the front desk checks if you have a visitor pass. If you do, they wave you through. If you forgot it, they politely point you to the reception desk first.

In a Laravel website, Middleware is that exact security guard. Every time someone visits a page on your site, their request passes through middleware before it ever reaches your Controller or View.

Why Do Beginners Need Middleware?

Without middleware, you would have to copy-paste the same "Are you logged in?" check at the top of every single page. Middleware lets you write that rule once and attach it to any route you want to protect.

  • Authentication: Make sure only logged-in users can open /dashboard.
  • Language Selection: Read the URL (like /id or /en) and switch the site language automatically.
  • Maintenance Mode: Show a friendly "Be right back!" page while you update your site.

How to Create Your First Middleware

You can ask Laravel's Artisan assistant to create a new middleware file for you with one short command:

# Create a new middleware called CheckAge
php artisan make:middleware CheckAge

Laravel creates the file at app/Http/Middleware/CheckAge.php. Inside, there is a handle function. Think of $next($request) as the guard saying, "Everything looks good, please go ahead!"

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAge
{
    public function handle(Request $request, Closure $next)
    {
        // Check if the visitor's age query is under 13
        if ($request->query('age') < 13) {
            // Stop here and send them back to the home page
            return redirect('/');
        }

        // Otherwise, let them continue to the page
        return $next($request);
    }
}

Attaching Middleware to a Route

Once your guard is ready, you can assign it to any route in routes/web.php using ->middleware(...):

use App\Http\Middleware\CheckAge;
use Illuminate\Support\Facades\Route;

// Only visitors who pass CheckAge can view /movies
Route::get('/movies', function () {
    return view('movies');
})->middleware(CheckAge::class);

3 Things to Remember

  • Middleware is a filter: It inspects incoming requests before your page logic runs.
  • $next($request) means "continue": Return a redirect to block, or return $next($request) to allow.
  • Write once, reuse everywhere: Attach one middleware to many routes to keep your code clean and safe.