Understanding Laravel Middleware: Creation, Registration, and Usage

This article explains what Laravel middleware is, how to create custom middleware with Artisan, the structure of the handle method, the difference between global and route middleware, how to register middleware in the Kernel, and various ways to assign middleware to routes or controllers, including parameter passing.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding Laravel Middleware: Creation, Registration, and Usage

In Laravel, middleware acts as an HTTP request filter that can execute logic before or after a request reaches the application.

Common Middleware Functions

Specify routes

Set HTTP response headers

Log requests

Filter request parameters

Enable/disable maintenance mode

Perform actions before or after the response

Creating Custom Middleware

Run the Artisan command to generate a middleware class: php artisan make:middleware <MiddlewareName> The command creates a file under app/Http/Middleware containing a handle method:

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfSuperAdmin {
    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        // Your logic here
        return $next($request);
    }
}

The handle method always receives the request object ( $request) and a closure ( $next) that forwards the request to the next middleware or the application.

Pre‑ and Post‑Middleware

Pre‑middleware runs before the request reaches the controller, while post‑middleware runs after the controller has generated a response.

Middleware Types

Global middleware – runs on every HTTP request.

Route middleware – runs only on routes to which it is attached.

Registering Middleware

All middleware must be registered in app/Http/Kernel.php. The file defines three arrays: $middleware: global middleware. $middlewareGroups: groups such as 'web' and 'api'. $routeMiddleware: individual route middleware keyed by name (e.g., 'auth', 'throttle').

Assigning Middleware to Routes or Controllers

Two main methods are available:

Via a controller’s constructor:

class ForumController extends Controller {
    public function __construct() {
        $this->middleware('auth');
    }
    // ... other actions ...
}

You can limit the middleware with except([...]) or only([...]).

Directly on a route definition:

Route::get('admin/profile', function () { /* ... */ })
        ->middleware('auth');
    // Or using a fully‑qualified class name
    Route::get('admin/profile', function () { /* ... */ })
        ->middleware(CheckAge::class);
    // Or grouping
    Route::group(['middleware' => ['web']], function () { /* ... */ });

Passing Parameters to Middleware

Parameters are appended after the middleware name, separated by commas:

Route::get('admin/profile', function () { /* ... */ })
    ->middleware('auth:admin,30,US');

In the middleware class, the handle signature can receive these extra arguments:

public function handle($request, Closure $next, $role, $age, $country) {
    // Use $role, $age, $country as needed
    return $next($request);
}

Summary of Steps

Generate middleware with php artisan make:middleware MiddlewareName.

Register it in app/Http/Kernel.php (global, group, or route).

Implement the desired logic inside the handle method.

Assign the middleware to routes or controllers, optionally using except, only, or passing parameters.

Using middleware helps protect routes, filter input, and perform common tasks without scattering logic throughout controllers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

middlewareHTTPLaravel
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.