Shahid
Shahid

Reputation: 357

Laravel: get translation from language file containing dot

Is it possible to get translation from language file that contains (.)dot?

For example, The language directory looks like

/lang
      /en
          pagination.php
          phone.history.php

     /es
          pagination.php
          phone.history.php

phone.history.php file contains dot and want to get translation for the key 'name' from phone.history.php file.

Lang::get('phone.history.name')

It doesn't work.

Upvotes: 4

Views: 3915

Answers (2)

Timo Heil
Timo Heil

Reputation: 1

There is actually a 3rd option which is to use dotted key names. So inside /lang/en/phone.php you can set 'history.name' => 'John Doe' and then retrieve that using trans('phone.history.name').

Upvotes: 0

Bogdan
Bogdan

Reputation: 44526

Actually the Laravel key used for translations can only contain one dot . in order to work and the function of that dot is to separate the translation file path (relative to the language directory) from the translation array key. That's because the Translator class extends the Illuminate\Support\NamespacedItemResolver class, which parses the key using the following logic:

  • First it determines if there is a namespace present (denoted by ::) and extracts it.
  • It then goes on to split the key into a group (which is the relative filepath) and an item (which is the translation array key).

So in your case since there is no namespace, when you use this:

Lang::get('phone.history.name')

The result is the following:

  • The filename will be phone
  • The translation array key will be history (instead of name)

And since there's no phone.php in your language directory, it won't work.


So you have two options here:

  1. Use another character in your filename so there's only one dot in the translator parameter, something like /lang/en/phone_history.php and then use Lang::get('phone_history.name').

  2. Use a subdirectory if you want to group some translation files, something like /lang/en/phone/history.php and then use Lang::get('phone/history.name') (unfortunately, as I said above you can only use one dot as a separator, so you can't use the multiple level dot notation as you would for a configuration file Lang::get('phone.history.name')).

Upvotes: 2

Related Questions