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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article