kendrick's avatar

Dynamic use of cities table

I have a cities_table which holds different cities.

Currently in a form, a user can choose a city like:

<select name="city_id"> 
	@include('partials.cities')
	// I use this partial to offer the correct translation of a city
	// <option value="1">{{__('cities.moscow')}}</option>   
</select> 

Here, I am manually listing all cities in order to translate the name based on the language of a user, then check if a city_id is equal to the request and insert the translated city string.

I could also loop over all cities like:

@foreach($cities as $city)
<option value="{{$city->id}}">{{$city->city}}</option>  
@endforeach

and then request the id & city. But it wouldn't be translated.

How could I make it more dynamic and scalable?

I though about adding a translation shortcut to the cities_table like trans => mw and then grab it like: {{__('cities.$request->shortcut')}} (if possible)

0 likes
4 replies
automica's avatar

If you use an accessor on your cities model you can run whatever method you are doing to translate your city name and output it as if it is a field from your cities table.

public function getTranslatedCityAttribute()
{
return $this->translateCity($this->city);
}

This would allow you to pass in the cities array with id and translatedName to build up your select list, rather than translating in the blade.

@foreach($cities as $city)
<option value="{{$city->id}}">{{$city->tranlatedCity}}</option>  
@endforeach

https://laravel.com/docs/8.x/eloquent-mutators

kendrick's avatar

@automica - Thank you. This seems like a very good way. How would you structure the translateCity method? What do you think about the shortcut logic I mentioned above?

automica's avatar
automica
Best Answer
Level 54

depends on how you are storing your translations.

Actually if you are using localisation, and your cities are keyed by name then you won't need the accessor and can just render the translation in the view using trans helper.

@foreach($cities as $city)
<option value="{{$city->id}}">{{ trans('city.' . $city->city) }}</option>  
@endforeach

https://laravel.com/docs/8.x/localization

Please or to participate in this conversation.