How to translate URL parameters/slugs
Closed this issue · 9 comments
With mcamara/laravel-localization I was able to do that with
Event::listen('routes.translation', function ($locale, $attributes) {
...
return $attributes;
});
And with Loki how?
What does this code exactly do?
If you want to translate the URL see this: https://github.com/laravelista/loki#usetranslatedurls-boolean
Fox example, I have these URLs:
English: /en/city/london
Italian: /it/città/londra
The static part of URL I could translate following your docs is the second segment, just following the locale code ("city" translated in Italian to "città"). I also need to translate the third segment that is an URL parameter that rapresents the name of the city you want to see. The translations of the city name is stored into the database so as mcamara do, trhough an event listener I'm currently able to return the translated segments dynamically generated. There is a functionality you have in plan to do for Loki?
@fede91it I just use slugs for each language. For example.
In your database, if you are using https://github.com/Astrotomic/laravel-translatable for your multilingual models, and you have a table for cities like so:
cities:
ID, postal_code
city_translations:
ID, city_id, locale, name, slug
You store the city name and slug in the City translation table, and then just pass the city slug (for the desired locale) in the URL and resolve it in your controller method.
If you are not storing city name/slug translations in your database (don't know why) but you still want to have them localized in the URL, then you will have to create a reference array for each locale. This would mean a lot of manual work. For example in your controller you will have something like this:
protected $index = [
'it' => [
'londra' => 'london'
]
];
function show($localizedCityName)
{
$locale = app()->getLocale();
$slug = $this->index[$locale][$localizedCityName];
$city = City::whereSlug($slug)->first();
return $city->name;
}
Unfortunately my case history is more complex, and each URL has to be translated using multiple criteria, so I really need a way to translate URLs as mcamara already does
If you could explain it to me, then maybe I would be able to help you.
I've given you two ways how you could handle something like this: dynamic from database and static from a variable. You are free to send a PR for me to review.
I understand now..
Great to hear this
Great 👍