Search

The Laravel Translator

November 30, 2016 —John Koster

The Translator class is the class that most developers will be used to interacting with. The Translator class is responsible for handling the interactions between the application and the underlying translation systems, such as interacting with translation file storage and the actual processing of language files. The Translator class internally contains an implementation of Illuminate\Translation\LoaderInterface, which is an instance of Illuminate\Translation\FileLoader by default.

The Translator exposes numerous functions in its public API. The Translator class implements Symfony's Symfony\Component\Translation\TranslatorInterface interface so it should look familiar to developers coming from a Symfony background.

The following explanations of the various API methods will be using the passwords group that ships with Laravel by default, unless stated otherwise. The file is located at /resources/lang/en/passwords.php. The contents of this file can be quickly reviewed in the previous section.

The Illuminate\Translation\Translator can be resolved from the application container using the translator name.

#has($key, $locale = null)

The has method determines if a translation exists. It accepts a $key, which corresponds to an array key within the translation group file, i.e., user. The method also accepts a $locale, which can be used to determine if a given key exists for a particular locale.

The following code examples will demonstrate the usage of the has method. The results of method call will appear above the method call as a comment.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// true
7$exists = $translator->has('passwords.reset');
8 
9// true
10$exists = $translator->has('passwords.reset', 'en');
11 
12// true
13$exists = $translator->has('passwords.reset', 'es');
14 
15// false
16$exists = $translator->has('passwords.does_not_exist');

Line 11 in the above code examples could possible seem confusing at first. The method call returns true even though there is no es locale by default. The method call returns true because Laravel supports a fallback locale, which will be used to look up translations if a translation does not exist for a particular locale. The method call can be forced to return false by modifying the fallback locale first:

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// Set the fallback locale.
7$translator->setFallback('es');
8 
9// false
10$exists = $translator->has('passwords.reset', 'es');

The above code method call will now evaluate to false, because the password.reset translation does not exist for the es locale. On line 5 it can be observed that the fallback locale had to be set using a call to the setFallback method. This is because the Translator returned by the application container is a singleton - meaning only one instance of the class exists. The fallback locale that is loaded from the configuration is set on the instance early on in the request life-cycle. Because of this, modifying the app.fallback_locale or app.locale configuration at runtime will not have an effect on the translator (assuming the configuration changes are made after the translator has loaded).

#get($key, array $replace = [], $locale = null)

The get method is used to return the translation for the given key. It defines a $key parameter which corresponds to an array key within the group file. It also accepts an array of replacements (which are passed through the $replace array parameter) and a $locale parameter, which can be used to specify the desired locale.

Replacements are passed as a key/value pair. The replacement keys will be matched to any placeholders within the translation. Placeholders begin with a single colon (:) followed by a name and a space. For example, in the validation.php language file, the following lines can be found:

1<?php
2 
3<?php
4 
5return [
6 
7 ...
8 
9 'accepted' => 'The :attribute must be accepted.',
10 'array' => 'The :attribute must be an array.',
11 
12 ...
13 
14];

In the above translation lines, :attribute is a placeholder than can be replaced using the $replace parameter. The following code examples will demonstrate the results of using the $replace parameter. The results will appear above the method call as a comment.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// The :attribute must be an array.
7$translator->get('validation.array');
8 
9// The provided value must be an array.
10$translator->get('validation.array', ['attribute' => 'provided value']);

It should be noted that the placeholder name in the $replace parameter should not contain the leading : character.

#trans($id, array $parameters = [], $domain = 'messages', $locale = null)

The trans method is identical in usage to the get method. It internally makes a call and returns the value of the get method, passing in the $id, $parameters and $locale. The $domain is not used and is completely ignored.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// The provided value must be an array.
7$translator->get('validation.array', ['attribute' => 'provided value']);
8 
9// The provided value must be an array.
10$translator->trans('validation.array', ['attribute' => 'provided value']);

The trans method exists to satisfy the requirements of Symfony's TranslatorInterface.

#choice($key, $number, array $replace = [], $locale = null)

The choice method is used to pluralize a given $key, translating it for the given $locale. The choice method accepts the $number of some collection of objects that it should use when making pluralization decisions. Like the get and trans methods, it also accepts and array of replacements, using the $replace array.

Pluralization of strings is a complicated problem to solve. The table located at http://www.unicode.org/cldr/charts/25/supplemental/language_plural_rules.html gives a sense of the differences between different locales and the rules of pluralization. While words in the English language, by comparison, are fairly simple to convert to their plural forms (see Str::plural in the Helpers chapter), it is difficult to produce a "one-size-fits-all" pluralization system. The pluralization system used in the Translator is built on Symfony's implementation, from the Translation Component.

Assuming the following group file is located at /resource/lang/en/plural.php:

1<?php
2 
3<?php
4 
5return [
6 'books' => 'There is one book.|There are :count books.',
7];

It should be noted that pluralized strings allow for multiple messages to be stored in one translation line. Messages are separated by the | character, and are ordered such that the message that corresponds to the lower $number appear first and messages that appear for any higher $number appear sequentially afterwards. The messages can also contain placeholders, and work just the same as the choice and trans functions (placeholders begin with one colon [:] character).

The following code example would select the first message:

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// There is one book.
7$translator->choice('plural.books', 1);

The following code example would select the second message:

1<?hpp
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// There are 4 books.
7$translator->choice('plural.books', 4, ['choice' => 4]);

The following code examples highlight some more ways the choice method can be called, and ways they will mostly appear within applications:

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// There are 4 books.
7$translator->choice('plural.books', 4, ['choice' => 4]);
8 
9// There is one book.
10$translator->choice('plural.books', 1, ['choice' => 1]);

See the section Pluralization section for more details specific to just the pluralization syntax.

#transChoice($id, $number, array $parameters = [], $domain = 'messages', $locale = null)

The transChoice is functionally identical to the choice method. It internally returns the value of the choice method using the $id, $number, $parameters and $locale parameters. The $domain parameter is not used and is completely ignored.

The transChoice method exists to satisfy the requirements of Symfony's TranslatorInterface.

#load($namespace, $group, $locale)

The load method internally makes a call to the load method on the current instance of the Illuminate\Translation\LoaderInterface implementation, which by default is an instance of FileLoader. The Translator additionally keeps an internal cache of the loaded messages.

#addNamespace($namespace, $hint)

The Translator class exposes the addNamespace method as part of its public API. The addNamespace internally makes a call to the addNamespace method on the current instance of the Illuminate\Translation\LoaderInterface implementation, which by default is an instance of FileLoader.

#parseKey($key)

The parseKey is used to parse a given $key into its namespace, group and item parts. The namespace refers to a custom namespace (or the default * namespace); the group refers to a particular file, such as passwords.php and the item refers to a particular key within the array returned by the file. The following code examples will show the return values of various calls to the parseKey method. The code samples will assume a $translator variable exists, holding a reference to a Translator object.

1<?php
2 
3$key = $translator->parseKey('passwords.reset');

The $key variable would contain an array with the following structure:

1array (size=3)
2 0 => string '*' (length=1) Namespace
3 1 => string 'passwords' (length=9) Group
4 2 => string 'reset' (length=5) Item

Passing *.passwords.reset to the parseKey method would return the same results. THe following example shows the resulting data structure when passing in a key with a custom namespace:

1<?php
2 
3$key = $translator->parseKey('custom::passwords.reset');

The $key variable would now contain an array with the following structure:

1array (size=3)
2 0 => string 'custom' (length=6) Namespace
3 1 => string 'passwords' (length=9) Group
4 2 => string 'reset' (length=5) Item

#setSelector(MessageSelector $selector)

The setSelector method sets a Symfony\Component\Translation\MessageSelector instance ($selector) for the Translator. The MessageSelector instance is used by the choice and transChoice methods for loading the correct translation message based on the count of a collection and a given locale. Essentially, the MessageSelector implements the pluralization rules when selecting translation strings.

It is possible to set define a custom MessageSelector and pass an instance into the Translator:

1<?php
2 
3use Symfony\Component\Translation\MessageSelector;
4 
5class CustomSelector extends MessageSelector {}
6 
7// Get a `Translator` instance from the application container.
8$translator = app('translator');
9 
10$translator->setSelector(new CustomSelector());
11 
12// CustomSelector
13get_class($translator->getSelector());

#getSelector()

The getSelector() method returns the instance of \Symfony\Component\Translation\MessageSelector that the translator is currently using. If no MessageSelector has been previously set, a new instance of MessageSelector is created and returned.

#getLoader()

The getLoader method is used to return the instance of the Illuminate\Translation\LoaderInterface implementation the translator is currently using. By default, this will be an instance of Illuminate\Translation\FileLoader, which is registered with the application container as a singleton (meaning only one instance is ever used throughout the application).

#getLocale()

The getLocale method is used to retrieve the current locale being used by the translator. The method is required by Symfony's TranslatorInterface.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// en
7$translator->getLocale();
8 
9// es
10$translator->setLocale('es');
11$translator->getLocale();

#locale()

The locale() method is functionally identical to the getLocale() method. It internally returns the value of the getLocale() method.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// true
7$same = ($translator->locale() === $translator->getLocale());

#setLocale($locale)

The setLocale method is used to set the locale that the translator should use. It accepts only one parameter $locale, which is the locale that should be set. By default, it is set to the value defined for locale in the app.php configuration file.

#getFallback()

The getFallback() method is used to return the fallback locale that the translator is currently using. A fallback locale is used when a translation for a different locale cannot be found.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// en
7$translator->getFallback();

#setFallback($fallback)

The setFallback method is used to set the fallback locale that the translator should use. It accepts only one parameter $fallback, which is the fallback locale that should be set. By default, it is set to the value defined for fallback_locale in the app.php configuration file.

1<?php
2 
3// Get a `Translator` instance from the application container.
4$translator = app('translator');
5 
6// Set the fallback to 'es'.
7$translator->setFallback('es');
8 
9// es
10$translator->getFallback();

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.