At one point or another, you may find yourself faced with the need for a route parameter that is consumed before the request hits the controller. You can achieve this using Laravel's routing events and/or middleware, but once you've finished, you'll notice that the controller is receiving the parameter, even though it doesn't need it.

Fortunately, Laravel's Route object has a method that can help us with this.

/**
 * Unset a parameter on the route if it is set.
 *
 * @param  string  $name
 * @return void
 */
public function forgetParameter($name)
{
    $this->parameters();

    unset($this->parameters[$name]);
}

Once you've extracted your route parameter, simply call the forgetParameter method, and it'll be as if it were never there to begin with.

public function handle(Request $request, Closure $next)
{
    // Get the parameter
    $param = $request->route()->parameter('param');

    // Forget the parameter
    $request->route()->forgetParameter('param');

    // Use the parameter
    // Code here...

    return $next($request);
}

Warning

This is a destructive action, as the parameter is unset from the stack and will no longer be available unless you're storing it somewhere.

When would I use this?

A great example of how this would be used is an application that's localised, using the first segment of the URL path as the locale to use for the request. The URL https://myapp.com/en/about would be represented by the route /{locale}/about, which would have a piece of middleware that extracts the {locale} variable, removes it from the stack, sets the applications' locale, and then continues on with the request.

I'm Ollie Read—a software architect, Laravel and PHP expert, and lifelong builder. I write to share what I learn, explore how things work, and help others.

Got thoughts, questions, or just want to chat? I'm always up for a good conversation— get in touch, or find me on BlueSky, X or Discord

Class
Route
Namespace
Illuminate\Routing
Description

This class represents both the registered route, and the current route state within Laravel.

Method
forgetParameter()
Class
Illuminate\Routing\Route
Parameters
string $name - The name of the parameter to forget.
Description

Unset a parameter on the route if it is set.

Links
Class
Route
Namespace
Illuminate\Routing
Description

This class represents both the registered route, and the current route state within Laravel.

Method
forgetParameter()
Class
Illuminate\Routing\Route
Parameters
string $name - The name of the parameter to forget.
Description

Unset a parameter on the route if it is set.

Links