Updated June 2026. Tested on Laravel 13 and PHP 8.4. Middleware aliases now live in bootstrap/app.php; the old HTTP Kernel is gone.
Middleware wraps a request: it runs code before or after your controller. Sometimes that code needs to know a value from the URL, like the {username} in a profile route. Reading route parameters in middleware is not done through the usual request input, so here is how.
A route with a parameter
Route parameters go in curly braces.
Route::get('/params/{name}', function (string $name) {
return $name;
});
Read the parameter in middleware
Generate a middleware.
php artisan make:middleware CheckName
Inside handle, use $request->route('name'), where name matches the parameter in the route.
public function handle(Request $request, Closure $next)
{
$name = $request->route('name');
// do something with $name
return $next($request);
}
To get every parameter at once, call $request->route()->parameters(), which returns them as an array.
$all = $request->route()->parameters(); // ['id' => 1, 'category' => 'books', 'name' => 'jane']
Register and apply the middleware
In current Laravel you give a middleware an alias in bootstrap/app.php.
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'check.name' => \App\Http\Middleware\CheckName::class,
]);
})
Then attach it to a route by that alias.
Route::get('/params/{name}', fn (string $name) => $name)
->middleware('check.name');
A real use: catch-all profile routes
Here is where this earns its keep. Say usernames live at the root, /{username}, so a profile is /jane. But some paths like /faq or /help are not profiles. Rather than declaring each fixed page before the catch-all, a middleware can check the parameter and divert.
public function handle(Request $request, Closure $next)
{
$reserved = ['faq', 'help', 'support'];
if (in_array($request->route('username'), $reserved, true)) {
return response()->view($request->route('username'));
}
return $next($request);
}
Now when someone visits /faq, the middleware sees that faq is a reserved word and serves the FAQ page instead of treating it as a username. Add a new reserved page by dropping it into the array.
That is reading route parameters in middleware: $request->route('name') for one, $request->route()->parameters() for all, and a tidy way to handle catch-all routes. Questions welcome in the comments.
All comments ()
No comments yet
Be the first to leave a comment on this post.