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.