user3253002
user3253002

Reputation: 1671

How to translate collections in Laravel 5?

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.

Upvotes: 0

Views: 2001

Answers (3)

Marek Gralikowski
Marek Gralikowski

Reputation: 1058

We can create custom Collection method.

Collection::macro('translate', function ($prefix) {
    return $this->map(function ($item) use ($prefix) {
        return trans($prefix . $item);
    });
});

in AppServiceProvider.

And usage:

Model::pluck('code_name', 'id')->translate('system.code.')->implode(',');

Upvotes: 1

user3253002
user3253002

Reputation: 1671

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!

Upvotes: 2

Helder Lucas
Helder Lucas

Reputation: 3343

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.

Upvotes: 1

Related Questions