Search code examples
phplaravellaravel-translatable

How to use Translatable fields in url parameters with route model binding?


I previously was using route-model binding with a customized key like so: Route::get('/{country:name}/{province:name}', [AdminController::class, 'locations']);

This worked great for a single language, but this app has to support 2 locales. I installed the spatie/laravel-translatable package so that the database could handle storing multiple languages.

This is great for accessing model properties like: $country->name and returning the proper language.

Now with the package, I can no longer access Models by customizing the key to the name because the name is now json in the DB.

How can I support multiple languages in the URL without just displaying the key? (While still using route-model binding)

The URL needs to be "nice" as in it does not show id's. I know that this could be done with slugs but that would require extra logic and a schema update, something that can't be done right now.


Solution

  • What i can suggest is that, you need to modify your Country model and put below function

    public function resolveRouteBinding($value, $field = null)
    {
        if (field == 'name') {
           return $this->where('name->'.app()->getLocale(), $value)->firstOrFail();
        }
    
        return parent::resolveRouteBinding($value, $field);
    }
    

    Here is for your reference https://laravel.com/docs/10.x/routing#customizing-the-resolution-logic