Search code examples
phplaravellocalizationlaravel-localization

Missing required parameter - routes with more than 2 parameters are not working with localization


I've been struggling lately with this problem and I really need some help.

So I implemented this tutorial: https://youtu.be/KqzGKg8IxE4 for adding localization to my project and it works well for routes that doesn't require another parameter besides the language. What I want to do is just keep the locale to the url as the first segment of the link, so it should follow this pattern:

  • example.com/en/shop
  • example.com/en/products/5/edit

but the routes with more parameters shouldn't be influenced by this prefix.

I have found more possible fixes for this, such as removing al the resource grouped routes and type them manually which would take forever, or override all the routes in order to use a parameter as a language switcher, for example 'example.com/shop?lang=en' and then implement an URL Generator macro, as answered in this question.

Also, I tried added an optional parameter in the language-switcher component, straight in my blade file like so

<language-switcher locale="{{ app()->getLocale() }}" 
     link-fr="{{ route(Route::currentRouteName(), ['locale' => 'fr', 'id' => '/{id?}']) }}" 
     link-en="{{ route(Route::currentRouteName(), ['locale' => 'en','id' => '/{id?}']) }}">
</language-switcher>

but what happens here is it just adds a random id for routes that do not have other parameter and only those which requires exactly 2 parameters work.

All these solutions are great BUT in my case none of them could be applied because as I said earlier, my requirement is to implement localization in such a way that the first segment of the link should be the language.

I feel there is an elegant way to solve this and I would appreciate any piece of advice since I no longer have any ideas on how this problem could be fixed.

Thank you !


Solution

  • You can get the current route parameters from the route object so something like:

    <language-switcher locale="{{ app()->getLocale() }}" 
         link-fr="{{ route(Route::currentRouteName(), array_merge(request()->route()->parameters(), [ 'locale' => 'fr' ])) }}" 
         link-en="{{ route(Route::currentRouteName(), array_merge(request()->route()->parameters(), [ 'locale' => 'en' ])) }}">
    </language-switcher>
    

    Note this assumes that there's a matched route which is generally true but will not be true when displaying certain error pages like a 404 page when a route was not matched. So something to be mindful of