Parameterized Middleware in Laravel

Last updated on by

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.

Senior Software Engineer • Staff Writer @ Laravel News • PHP, Laravel, Livewire, TailwindCSS, VueJS & InertiaJS • Co-organizer @ Laravel Greece Meetup

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy

Laravel Forge

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

Laravel Forge

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell

NativePHP

Build rich mobile apps across iOS and Android from a single Laravel codebase. This changes everything!

NativePHP

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce

LaraJobs

The official Laravel job board

LaraJobs

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →

Generate awesome open graph images with Open Graphy

Read article

Defining a Dedicated Query Builder in Laravel 12 With PHP Attributes

Read article

Tracking Cache Activity with Laravel Events

Read article

Building a Task Reminder With Laravel and MongoDB

Read article

Generate Eloquent Models from Database Markup Language Files

Read article

Retrieving Command Parameters in Laravel Artisan

Read article