How to translate collections in Laravel 5?

2019-09-05 15:02发布

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.

标签: php laravel-5
2条回答
霸刀☆藐视天下
2楼-- · 2019-09-05 15:24

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!

查看更多
Animai°情兽
3楼-- · 2019-09-05 15:42

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.

查看更多
登录 后发表回答