Laravel Tutorials

Parameterized Middleware in Laravel

Published
Parameterized Middleware in Laravel image

Laravel's middleware system becomes more powerful with parameter passing, allowing dynamic behavior based on runtime values. This feature is particularly useful for role-based access control, rate limiting, or any scenario requiring configurable middleware logic.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureUserHasRole
{
    public function handle(Request $request, Closure $next, string ...$roles)
    {
        if (!$request->user()?->hasAnyRole($roles)) {
            return response()->json([
                'error' => 'Insufficient permissions'
            ], 403);
        }
        return $next($request);
    }
}

Let's explore how to implement role-based route protection:

use App\Http\Controllers\PostController;
use App\Http\Middleware\EnsureUserHasRole;

Route::prefix('posts')->group(function () {
    // Public routes
    Route::get('/', [PostController::class, 'index']);
    
    // Editor routes
    Route::put('/{id}', [PostController::class, 'update'])
        ->middleware(EnsureUserHasRole::class . ':editor');
        
    Route::post('/', [PostController::class, 'store'])
        ->middleware(EnsureUserHasRole::class . ':editor');
    
    // Admin routes
    Route::delete('/{id}', [PostController::class, 'destroy'])
        ->middleware(EnsureUserHasRole::class . ':admin');
});

Parameterized middleware provides a clean way to implement dynamic authorization rules while keeping your routes and controllers lean.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article