DEV Community

Muhammmad Nawaz
Muhammmad Nawaz

Posted on • Originally published at 127.0.0.1

Laravel Middleware

What is Middleware in Laravel?

In Laravel, Middleware acts as a bridge between a request and a response. It filters incoming HTTP requests before they reach the controller and can modify the response before sending it back to the user.

Think of it as a gatekeeper for your application routes.

**

1. Built-in Middleware in Laravel**

Laravel ships with several pre-built middleware:

  • **auth** – Ensures only logged-in users access a route.
  • **guest** – Redirects authenticated users away from guest-only pages.
  • **throttle** – Limits repeated requests to prevent abuse.
  • **verified** – Checks if a user’s email is verified.
  • **csrf** – Protects against cross-site request forgery attacks.

2. Creating Custom Middleware

You can create your own middleware using:

php artisan make:middleware CheckAdmin
Example (app/Http/Middleware/CheckAdmin.php):

public function handle($request, Closure $next)
{
if (auth()->user()?->is_admin) {
return $next($request);
}
return redirect('/')->with('error', 'Access denied.');
}
This ensures only admins can access certain routes.

**

3. Registering Middleware**

There are two ways:

  • Global Middleware → Runs on every request (app/Http/Kernel.php).
  • Route Middleware → Apply only on specific routes:

Route::middleware(['auth', 'checkadmin'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});

4. Use Cases of Middleware

  • 🔒 Security → Authentication, CSRF, input sanitization.
  • 🌍 Localization → Set app language based on user’s location.
  • 📊 Analytics → Log every request for monitoring.
  • Rate Limiting → Control API usage with throttle.

Why Middleware is Important?

  • Keeps code clean and reusable.
  • Adds extra security layers.
  • Helps enforce policies and roles without bloating controllers.

Top comments (0)