0
0
LaravelConceptBeginner · 3 min read

What is Route Middleware in Laravel: Simple Explanation and Example

In Laravel, route middleware is a way to filter HTTP requests entering your application before they reach your routes or controllers. It acts like a checkpoint that can allow, block, or modify requests based on conditions such as authentication or user roles.
⚙️

How It Works

Think of route middleware as a security guard at the entrance of a building. Before someone enters, the guard checks if they have the right ID or permission. Similarly, Laravel middleware checks incoming requests before they reach your app's routes.

When a request comes in, Laravel runs it through any middleware assigned to that route. The middleware can decide to let the request continue, redirect it elsewhere, or stop it completely. This helps keep your app organized and secure by handling common tasks like authentication, logging, or input validation in one place.

💻

Example

This example shows a simple middleware that checks if a user is authenticated before allowing access to a route.

php
<?php
// app/Http/Middleware/CheckAuthenticated.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAuthenticated
{
    public function handle(Request $request, Closure $next)
    {
        if (!auth()->check()) {
            return redirect('/login');
        }
        return $next($request);
    }
}

// In routes/web.php
use App\Http\Middleware\CheckAuthenticated;

Route::get('/dashboard', function () {
    return 'Welcome to your dashboard!';
})->middleware(CheckAuthenticated::class);
Output
If user is logged in: Displays 'Welcome to your dashboard!' If not logged in: Redirects to '/login' page
🎯

When to Use

Use route middleware when you want to control access or modify requests for specific routes. Common uses include:

  • Checking if a user is logged in before accessing private pages.
  • Restricting routes to users with certain roles or permissions.
  • Logging or modifying requests globally or for certain routes.
  • Protecting routes from spam or bots.

Middleware helps keep your route logic clean by separating these checks from your main code.

Key Points

  • Middleware acts as a filter for HTTP requests before they reach routes.
  • It can allow, redirect, or block requests based on custom logic.
  • Route middleware is assigned to specific routes or groups of routes.
  • Commonly used for authentication, authorization, and request modification.

Key Takeaways

Route middleware filters requests before they reach your Laravel routes.
It is useful for tasks like authentication and access control.
Middleware keeps your route code clean by handling common checks separately.
You assign middleware to routes to protect or modify them as needed.