Why might you want to forget a route parameter?

And how does it work?

Joel Clermont
Joel Clermont

I've written before about a simple approach to localizing a Laravel app with middleware.

One variation of this is to have the locale in the URL path, not just in the query string. For example, /{lang}/some/path.

This works well, but one thing that becomes cumbersome is that you then have to type hint the locale in every controller method. Or do you?

Laravel has a method called forgetParameter on the Route class. This allows you to remove a parameter from the route, which means you can use it in the middleware to set the locale, but then remove it before it gets to the controller, avoiding the need to type hint it.

Here's what it might look like:

// inside your Localization middleware
public function handle(Request $request, Closure $next)
    // logic to determine the requested $language removed for brevity


    $request->route()->forgetParameter('lang'); // this drops the parameter from the route

    return $next($request);

Here to help,


P.S. Learn why you should never use unvalidated request data in our book, Mastering Laravel Validation Rules.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.