0
0
LaravelHow-ToBeginner · 3 min read

How to Use Middleware in Route in Laravel: Simple Guide

In Laravel, you use middleware in routes by adding the middleware() method to your route definition. This method accepts the middleware name(s) as a string or array to apply specific logic before the route executes.
📐

Syntax

To use middleware in a Laravel route, you attach it using the middleware() method on the route definition. You can pass a single middleware as a string or multiple middlewares as an array.

  • Route::get(...)->middleware('auth'): Applies the 'auth' middleware to the route.
  • Route::post(...)->middleware(['auth', 'verified']): Applies multiple middlewares in order.
php
Route::get('/dashboard', function () {
    // Your code here
})->middleware('auth');

Route::post('/profile', function () {
    // Your code here
})->middleware(['auth', 'verified']);
💻

Example

This example shows a route that uses the built-in auth middleware to restrict access to authenticated users only. If a user is not logged in, they will be redirected to the login page automatically.

php
<?php

use Illuminate\Support\Facades\Route;

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

Common Pitfalls

Common mistakes when using middleware in routes include:

  • Forgetting to register custom middleware in app/Http/Kernel.php.
  • Passing middleware names incorrectly (e.g., using class names instead of registered keys).
  • Not applying middleware to the correct route or group.

Always ensure middleware is registered and referenced by its key.

php
/* Wrong way: Using class name directly without registration */
Route::get('/admin', function () {
    // admin page
})->middleware(\App\Http\Middleware\CheckAdmin::class);

/* Right way: Register middleware in Kernel.php and use key */
// In app/Http/Kernel.php
// 'admin' => \App\Http\Middleware\CheckAdmin::class,

Route::get('/admin', function () {
    // admin page
})->middleware('admin');
📊

Quick Reference

Summary tips for using middleware in Laravel routes:

  • Use middleware('name') to apply middleware to a single route.
  • Use middleware(['name1', 'name2']) to apply multiple middlewares.
  • Register custom middleware in app/Http/Kernel.php before use.
  • Group routes with middleware using Route::middleware('name')->group(function () { ... }).

Key Takeaways

Attach middleware to routes using the middleware() method with middleware keys.
Register custom middleware in app/Http/Kernel.php before applying it to routes.
You can apply one or multiple middlewares by passing a string or array respectively.
Middleware controls access or modifies requests before the route logic runs.
Use route groups to apply middleware to many routes at once for cleaner code.