0
0
LaravelConceptBeginner · 3 min read

What is Middleware in Laravel: Explanation and Example

Middleware in Laravel is a way to filter HTTP requests entering your application. It acts like a gatekeeper that can inspect, modify, or block requests before they reach your routes or controllers.
⚙️

How It Works

Think of middleware as a security guard or a checkpoint on a road. When a request tries to enter your Laravel app, the middleware checks it first. It can decide if the request should continue, be changed, or be stopped.

For example, middleware can check if a user is logged in before allowing access to certain pages. If the user is not logged in, the middleware can redirect them to a login page. This happens automatically before your main code runs.

This system helps keep your app organized and secure by separating these checks from your main business logic.

💻

Example

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

php
<?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 middleware when you want to run checks or actions on requests before they reach your app's core logic. Common uses include:

  • Checking if a user is logged in (authentication)
  • Verifying user roles or permissions (authorization)
  • Logging or modifying requests
  • Handling CORS (Cross-Origin Resource Sharing) settings
  • Redirecting users based on conditions

Middleware helps keep your code clean by separating these concerns from your main controllers or routes.

Key Points

  • Middleware acts as a filter for HTTP requests in Laravel.
  • It can allow, modify, or block requests before they reach your app.
  • Commonly used for authentication, authorization, and request modification.
  • Middleware keeps your app organized by separating concerns.
  • You can apply middleware globally or to specific routes.

Key Takeaways

Middleware filters HTTP requests before they reach your Laravel app's core logic.
Use middleware to handle authentication, authorization, and request modifications.
Middleware helps keep your code clean by separating request checks from main code.
You can apply middleware globally or on specific routes for flexible control.