I am using the pluck method to retrieve values. How can I translate these values? (these values are options for a selection input field)
$relationtypes = Relationtype::pluck('name', 'id');
My relationtypes are: supplier, customer, etc.
I am using the pluck method to retrieve values. How can I translate these values? (these values are options for a selection input field)
$relationtypes = Relationtype::pluck('name', 'id');
My relationtypes are: supplier, customer, etc.
I also found a more convenient solution:
$relationtypes = RelationType::pluck('name', 'id')->map(function ($item, $key) {
return trans('labels.' . $item . '');
});
Passing this to your view, you can use:
{!! Form::select('relationtypes[]', $relationtypes,
isset($relation) ? $relation->relationtypes->pluck('id')->toArray() : 0, ['class' => 'form-control']) !!}
Hope this helps other people!
Your controller method may look like:
public function index () {
$relationtypes = Relationtype::pluck('name', 'id');
// A better place for this might be a middleware
App::setlocale('your-locale');
return view('relationtypes.index, compact('relationtypes'));
}
In your view iterate over them:
<select>
@foreach (types as type)
<option value="{{ type.id }}">{{ trans(type.name) }}</option>
@endforeach
</select>
If you want to translate the values using the trans
function you'll need to have beforehand the values in resources\lang\<locale>\<file>.php
For example, lets image the values from your database are:
| id | name |
|----|------------|
| 1 | slug-one |
| 2 | slug-two |
| 3 | slug-three |
Then in resources\lang\nl\slugs.php
return [
'slug-one' => 'whatever translation for slug-on in nl',
// ...
];
This approach is good for non dynamic values, if your values are dynamic the translation probably must be in some db field like: name_nl
, name_en
maybe?
But there are lots of packages for this problem already.