Laravel 5: String Translation Public API

February 20, 2018 —John Koster

The "Illuminate\Translation\Translator" class is the class that most Laravel developers will become the most familiar with when interacting with the Laravel translation services. The Translator class is responsible for handling the interactions between the application business logic 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\Contracts\Translation\Loader", which is an instance of "Illuminate\Translation\FileLoader" by default.

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 article Laravel 5: The Translator's File Loader.

An instance "Illuminate\Translation\Translator" can be resolved from the application container using the translator name.

#Retrieving Translation Line Text With get

The get method can be used to retrieve the translation line for the provided $key. This method can also process any replacements within the translation line itself (by passing an array argument for the $replace parameter). This method also defines a $locale and $fallback parameter, these will be discussed in further detail below.

By default, this method will use a fallback locale.

#Signature

The signature of the get method is:

1public function get(
2 $key,
3 array $replace = [],
4 $locale = null,
5 $fallback = true
6);

#Example Use

In the following examples, we will look at the various ways we can invoke the get method. We will start with simple translation line retrieval and gradually work through using the remaining parameters.

#Retrieving Translation Lines

The simplest way to use the get method is to simply ask it to get the value of a translation line. In the following example, we will retrieve the validation.accepted translation line (we will continue to reference the validation translation lines throughout these examples for consistency):

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.accepted translation line.
5$line = $translator->get('validation.accepted');

Once the above code has executed, the $line variable would contain the value The :attribute must be accepted.. The :attribute part of the translation line indicates that we can pass in a value to dynamically change the translation message.

One thing to take note of when using the get method (or any method that returns translation lines), is that if the translator cannot find the translation key requested, it will return the translation key itself as the result. This will become more clear in the following example:

1// As the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Ask the translator for a translation line
5// that we know does not exist.
6$line = $translator->get('validation.key_that_does_not_exist');

When we request a translation line that does not exist, the translator returns the key itself as the result. This makes it easy to spot missing translation keys when interacting with user interfaces or examining application output. In our example above, the $line variable would contain the value validation.key_that_does_not_exist.

#Providing Replacements for Translation Lines

In the previous example, we looked at how to retrieve individual translation lines. In this section, we will look at how to process replacements with the translator. Replacements are supplied 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 
3return [
4 
5 // ...
6 
7 'accepted' => 'The :attribute must be accepted.',
8 'array' => 'The :attribute must be an array.',
9 
10 // ...
11 
12];

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// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// The :attribute must be an array.
5$translator->get('validation.array');
6 
7// The provided value must be an array.
8$translator->get('validation.array', [
9 'attribute' => 'provided value'
10 ]);

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

#Specifying a Locale

By default, the get method will look for the translation lines using the locale specified as the default with the translation service. However, we can specify a locale by supplying an argument for the $locale parameter. For the following example, we will create the following language file at resources/lang/es/validation.php:

1<?php
2 
3return [
4 
5 'accepted' => 'Los :attribute deben ser aceptados.',
6 
7];

After we have created or sample language file, we can use the following to request the translation line for the new locale:

1// As the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.accepted translation line.
5$line = $translator->get('validation.accepted', [], 'es');

Let's see what happens when we attempt to retrieve a translation line from the es locale that we know has not been defined:

1// As the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.array translation line.
5$line = $translator->get('validation.array', [], 'es');

When we request a translation line from a different locale, by default the translator will look at the fallback locale to attempt to resolve the translation line. Because of this, we will get The :attribute must be an array. line as the result since the validation.array translation line has been defined for the en locale.

This is useful in some situations, but it might be helpful to see which translation keys have not been defined for all locales.

#Suppressing Fallback Local Translation Lines

When building multi-lingual applications, it is often necessary to translate messages into multiple languages; often times translations are not always available at the time of release. To help us handle this situation, Laravel supports the concept of a "fallback locale", which let's us use the translation lines from our default locale when a translation line is not available in the other locales. However, this can make it difficult at times to quickly spot which lines have not been translated into the other locales, we can disable this behavior by making use of the $fallback parameter:

1// As the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.array translation line.
5$line = $translator->get('validation.array', [], 'es', false);

In the above code example, we have supplied a falsey value for the $fallback parameter; after the code has executed, the $line variable would contain the value validation.array. If toggling this behavior is something you would like to do often, it is important to note that the trans helper method will always use a fallback locale; at the time of writing, this cannot be adjusted through configuration.

#Retrieving Translation Lines from JSON Language Files With getFromJson

The getFromJson method is similar to the get method, but allows you to retrieve translation lines from JSON-based language files. It accepts many of the same parameters, but does not allow us to specify a fallback locale (if a translation line cannot be found in the JSON-based language files, Laravel will start to look in the standard PHP-based translation files for developer convenience).

#Signature

The signature of the getFromJson is:

1public function getFromJson(
2 $key,
3 array $replace = [],
4 $locale = null
5);

#Example Use

For the following examples, we will create a new JSON-based language file at resources/lang/example.json:

1{
2 "validation.accepted": "The :attribute is required, resolved from
3 our example JSON file."
4}

In the following example, we will use the getFromJson method to first retrieve the translation line as well as process replacements:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve our example message. The returned value will be:
5// The :attribute is required, resolved from our example JSON file.
6$line = $translator->getFromJson('validation.accepted',
7 [], 'example');
8 
9// Retrieve example with replacements. The returned value will be:
10// The name is required, resolved from our example JSON file.
11$replacementLine = $translator->getFromJson('validation.accepted', [
12 'attribute' => 'name'
13 ], 'example');
14 
15// Attempt to retrieve a translation line that we have not
16// defined in our JSON-based language file. The result is:
17// The :attribute must be an array.
18$fallbackBehavior = $translator->getFromJson('validation.array',
19 [], 'example');

You will notice that the value of the $fallbackBehavior invocation has defaulted to the PHP-based language files. This allows developers to use the __ global helper function without having to worry about distinguishing between the use of the trans or __ helper function.

#Translating Strings With trans

The trans method is similar to the get method, and can be used in a similar way. The difference between the two methods is that the trans method does not allow you to change the fallback locale behavior, and defaults to always using the fallback locale for translation lines that have not been defined in other locales.

#Signature

1public function trans(
2 $key,
3 array $replace = [],
4 $locale = null
5);

#Example Use

The following examples will demonstrate how to make equivalent calls between the trans and the get method. For more detailed explanation of each of the parameters, see the section on the get method.

In the following example, we will use the trans method to retrieve an individual translation line:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.accepted translation line.
5$getLine = $translator->get('validation.accepted');
6$transLine = $translator->trans('validation.accepted');

Retrieving translation lines with replacement attributes is also possible with the trans method:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// The :attribute must be an array.
5$translator->get('validation.array');
6 
7$translator->trans('validation.array');
8 
9// The provided value must be an array.
10$translator->get('validation.array', [
11 'attribute' => 'provided value'
12 ]);
13 
14$translator->trans('validation.array', [
15 'attribute' => 'provided value'
16 ]);

The following example demonstrates how to specify a locale using the trans method, and assumes the following language file is available at resources/lang/es/validation.php:

1<?php
2 
3return [
4 
5 'accepted' => 'Los :attribute deben ser aceptados.',
6 
7];

We can now use the trans method to retrieve the translation lines from other locales:

1// As the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Retrieve the validation.accepted translation line.
5$line = $translator->get('validation.accepted', [], 'es');
6$transLine = $translator->trans('validation.accepted', [], 'es');

#Determining if a Translation Line Exists With has

The has method determines if a translation line exists for the specified locale. 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.

#Signature

The signature of the has method is:

1 
2public function has(
3 $key,
4 $locale = null,
5 $fallback = true
6);

#Example Use

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// Get a translator instance from the Service Container.
2$translator = app('translator');
3 
4// true
5$exists = $translator->has('passwords.reset');
6 
7// true
8$exists = $translator->has('passwords.reset', 'en');
9 
10// true
11$exists = $translator->has('passwords.reset', 'es');
12 
13// false
14$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// Get a translator instance from the Service Container.
2$translator = app('translator');
3 
4// Set the fallback locale.
5$translator->setFallback('es');
6 
7// false
8$exists = $translator->has('passwords.reset', 'es');

The above code method invocation 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).

We've seen how to manipulate the results of the has method to when working with multiple locales by invoking the setFallback method, but we can also do this by manipulating the $fallback parameter. In the following example, we will indicate to the translation service that we do not want to look at the fallback locale when determining if a translation line exists:

1// Get a translator instance from the Service Container.
2$translator = app('translator');
3 
4// Indicate to the translation service that we do not
5// want to look at the fallback locale when checking
6// if a translation line has been defined.
7$exists = $translator->has('passwords.reset', 'es', false);

After the code in the previous example has been executed, the $exists variable would contain the value false. Since this is a common thing to do, Laravel provides an additional method to help make the intent of the method call clearer to developers: hasForLocale. We will investigate this method in the next section.

#Determining if a Locale Has a Translation Line With hasForLocale

The hasForLocale is a convenient method to help check if a translation line has been defined for a given locale. its default behavior is to look in the default locale for the requested translation $key, but we can request information about any locale by supplying a string argument for the $locale parameter.

The hasForLocale method is a wrapper around the has method.

#Signature

1public function hasForLocale(
2 $key,
3 $locale = null
4);

#Example Use

In the following example, we will check if various translation lines have been defined for different locales. The results of the operation will appear above the method call as either true or false. The following examples will assume the following language files are available:

resources/lang/en/validation.php:

1<?php
2 
3return [
4 
5 // ...
6 
7 'accepted' => 'The :attribute must be accepted.',
8 'active_url' => 'The :attribute is not a valid URL.',
9 
10];

resources/lang/es/validation.php:

1<?php
2 
3return [
4 
5 'accepted' => 'Los :attribute deben ser aceptados.',
6 
7];
1// Get a translator instance from the Service Container.
2$translator = app('translator');
3 
4// true
5$exists = $translator->hasForLocale('validation.accepted');
6 
7// true
8$exists = $translator->hasForLocale('validation.accepted', 'es');
9 
10// false
11$exists = $translator->hasForLocale('validation.active_url', 'es');
12 
13// false
14$exists = $translator->hasForLocale('validation.accepted', 'it');

#Translating Strings Based on a Number of Items With choice

The choice method is used to pluralize the specified translation $key. This method is often used to translate text based on a certain number of items. A good example is an application that displays user messages, and would like the ability to display either You have one unread message or You have unread messages based on the number of unread messages.

#Signature

The signature of the choice method is:

1public function choice (
2 $key,
3 $number,
4 array $replace = [],
5 $locale = null
6);

#Example Use

Pluralization of strings is a complicated problem to solve. The table located at https://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 String Helpers chapter), it is difficult to produce a "one-size-fits-all" pluralization system.

For the examples in this section, we will create a new language file at resources/lang/en/plural.php. The language file we will create may have some syntax that is unfamiliar, or intimidating at first, but we will cover the pluralization message syntax in further detail in a later section. For now, let's just focus on how to interact with the translator's choice method.

resources/lang/en/plural.php:

1<?php
2 
3return [
4 
5 'messages' => 'You have one unread message.
6 |You have unread messages.',
7 
8 'messages_attributes' => 'You have one unread message.
9 |You have :count unread messages.',
10 
11 'messages_with_zero' => '{0} You\'re all caught up!
12 |[1] You have on unread message.
13 |[2,*] You have :count unread messages'
14];

I've formatted the localization messages onto multiple lines for readability. If you choose to do this, be aware that the newline characters will become part of the translation output.

In the following examples, we will look at the various ways that we can call the choice method:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Get the translation for one item.
5$messageSingle = $translator->choice('plural.messages', 1);
6 
7// Get the translation for many items.
8$messageMany = $translator->choice('plural.messages', 2);
9 
10// Get the translation for one item.
11$messageAttributesSingle = $translator->choice(
12 'plural.messages_attributes',
13 1
14 );
15 
16// Get the translation for two items, with attribute replacement.
17$messageAttributesMany = $translator->choice(
18 'plural.messages_attributes',
19 2, [
20 'count' => 2
21 ]
22 );
23 
24// Get the translation for a collection with no items.
25$messagesWithZero = $translator->choice(
26 'plural.messages_with_zero',
27 0
28 );
29 
30// Get the translation for a collection with one item.
31$messagesWithZeroSingle = $translator->choice(
32 'plural.messages_with_zero',
33 1
34 );
35 
36// Get the translation for a collection of two
37// items with attribute replacement.
38$messagesWithZeroMany = $translator->choice(
39 'plural.messages_with_zero',
40 2, [
41 'count' => 2
42 ]
43 );

Let's examine the output of each translation line after the code has executed. The results will be displayed in a table to make it easier to compare the results:

Variable Returned Value
$messageSingle You have on unread message.
$messageMany You have unread messages.
$messageAttributesSingle You have one unread message.
$messageAttributesMany You have 2 unread messages.
$messagesWithZero You're all caught up!
$messagesWithZeroSingle You have one unread message.
$messagesWithZeroMany You have 2 unread messages.

#Determining the Count of Items in a Collection

In the previous example, we looked many ways to call the choice method, including out to pass in replacement parameters. In many of the examples, we passed in number to indicate the number of items in a collection. The choice method will allow you to pass in any object that implements PHP's Countable interface for the $number parameter (some examples are PHP arrays as well as Laravel collections). In the following example, we will pass these items directly into the choice method:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Create our sample messages array.
5$messages = [
6 'Welcome to our service...',
7 'Thank you!',
8 'Another example message...',
9];
10 
11// Call the choice method by passing in our messages array.
12$countableExample = $translator->choice(
13 'plural.messages_with_zero',
14 $messages, [
15 'count' => count($messages),
16 ]
17 );

After the above code has executed, the $countableExample will contain the value You have 3 unread messages. You will notice that we still had to call PHP's count function when supplying the number of items in our attributes array.

#Specifying the Locale

Like with many of the translator's public methods, we can specify the locale when calling the choice method via an argument to the $locale parameter. By default, Laravel will use the default configured locale when you invoke the choice method.

We will use the following file at resources/lang/es/plural.php for the following examples:

Note: At the time of writing, using JSON-based language files does not work for the choice method.

resources/lang/es/plural.php:

1<?php
2 
3return [
4 
5 'messages' => 'no hay mensajes nuevos
6 |Tienes mensajes no leídos',
7 
8];

With the new language file in place, we can now instruct the translator to use it when calling the choice method like so:

1<?php
2// Ask the Service Container for a new translator instance.
3$translator = app('translator');
4 
5// Create our sample messages collection.
6$messages = collect([
7 'Welcome to our service...',
8 'Thank you!',
9 'Another example message',
10]);
11 
12$localeExampleSingle = $translator->choice(
13 'plural.messages', 1, [], 'es'
14 );
15 
16$localeExampleMultiple = $translator->choice(
17 'plural.messages', $messages, [], 'es'
18 );

After the above code has executed, the results would be:

Variable Returned Line
$localeExampleSingle no hay mensajes nuevos
$localeExampleMultiple Tienes mensajes no leídos

#The transChoice Method

The Laravel translator also exposes a transChoice method which just acts as an alias to the choice method for backwards compatibility. Their signatures and behavior are the same.

#Loading Translation Text Lines With load

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

For more examples on how to call the load method, refer to the load section in the FileLoad Public API chapter.

#Signature

The signature for the load method is:

1public function load(
2 $namespace,
3 $group,
4 $locale
5);

#Loader load vs. Translator load

Both the translator and file loader instances expose a load method with similar parameters, however, their usage is different. The loader, by design, is responsible for returning an array of the translation lines for the given $namespace, $group, and $locale combination. The translator instance takes the results of the loader and uses it to build its internal cache.

#Retrieving the Translation Loader With getLoader

The getLoader method is used to return the instance of the
"Illuminate\Contracts\Translation\Loader" 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).

Use this method in order to interact with the loader interface's API. The translator itself exposes methods that call out to the loader for convenience; these are documented in this section and will refer to the file loader sections in this book.

#Signature

The signature of the getLoader method is:

1public function getLoader();

#Adding Translation Namespaces With addNamespace

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\Contracts\Translation\Loader" implementation, which by default is an instance of FileLoader.

For more examples on how to call the addNamespace method, refer to the addNamespace section in the FileLoad Public API chapter.

#Signature

The signature of the addNamespace method is:

1public function addNamespace(
2 $namespace,
3 $hint
4);

The parameters of this method match the parameters of the loader's addNamespace method.

#Adding JSON Translation Files With addJsonPath

The addJsonPath is used to add a new JSON language file path to the file loader. This method will internally call the addJsonPath on the translator's addJsonPath method.

For more examples on how to call the addJsonPath method, refer to the addJsonPath section in the FileLoad Public API chapter.

#Signature

The signature of the addJsonPath method is:

1public function addJsonPath(
2 $path // The file path of the JSON language file.
3);

#Adding Arbitrary Translation Lines With addLines

The addLines method can be used to add arbitrary translation lines to the translator's translation lines collection for the provided locale. This method can be used to add translation lines at runtime in response to dynamic conditions within your application.

#Signature

The signature for the addLines method is:

1public function addLines(
2 array $lines,
3 $locale,
4 $namespace = '*'
5);

#Example Use

The following example demonstrates how to use the addLines method to add lines to the existing translator instance. We need to supply it a locale, but we will explore methods to do this dynamically based on the currently configured default locale.

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Get a translation line before calling addLines.
5$beforeAddLinesCall = $translator->get(
6 'addlines.test'
7 );
8 
9// Add a new translation line to the translator.
10$translator->addLines([
11 'addlines.test' => 'A new line',
12 ], 'en'
13 );
14 
15// Get a translation line after calling addLines.
16$afterAddLinesCall = $translator->get(
17 'addlines.test'
18 );

After the above code has executed, the new translation line will have been added to the translator instance. Let's take a step back to analyze the values of the variables before and after the call to the addLines method.

The value of the $beforeAddLinesCall method will be addlines.test, since the translator will simply return the translation key since it has not been added to the translator instance yet. After the call to addLines, the value of $afterAddLinesCall will be A new line since the translator now has an entry for the addlines.test translation key.

You will also notice that we had to specify the en locale when adding the translation key; this makes sense since the translator needs to know which key to map the translation line to.

However, there may be situations where we need to add translations to the translator instance without knowing what the currently configured locale is. We can do this by passing the results of the getLocale() method to the addLines method:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Get the current locale.
5$currentLocale = $translator->getLocale();
6 
7// Add a new translation to the translator.
8$translator->addLines([
9 'addlines.test' => 'A new line',
10 ], $currentLocale);

The translator instance also exposes a locale method, which is just an alias of the getLocale method; both of these methods return the same result.

#Parsing Translation Keys With parseKey

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 results returned from various calls to the parseKey method.

The return value of the parseKey method will be an array.

#Signature

The signature of the parseKey method is:

1public function parseKey(
2 $key
3);

#Example Use

The following example will demonstrate how to call the parseKey method to return information about the translation key:

1$parts = $translator->parseKey('passwords.reset');

After the above code has executed, the $parts array would contain the following information:

Index Value
0 *
1 passwords
2 reset

We will now examine the results of the parseKey method when we supply it a value that contains a custom namespace:

1$namespaceParts = $translator->parseKey(
2 'namespace::passwords.reset',
3 );
Index Value
0 namespace
1 passwords
2 reset

#Working with Translator Message Selectors

Each translator instance contains an instance of "Illuminate\Translation\MessageSelector", which is used to determine which translation line should be returned when using the choice or transChoice methods. The translator allows you to retrieve the current MessageSelector instance as well as set your own.

#Retrieving a Message Selector Instance With getSelector

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

#Signature

The signature of the getSelector method is:

1public function getSelector();

#Example Use

The following example will resolve a translator instance from the service container and get the current MessageSelector instance.

1<?php
2// Ask the Service Container for a translator instance.
3$translator = app('translator');
4 
5// Get the current MessageSelector
6$messageSelector = $translator->getSelector();

#Setting the Message Selector Instance With setSelector

The setSelector method can be used to set which MessageSelector instance is used by the translator.

#Signature

The signature of the setSelector method is:

1public function setSelector(
2 \Illuminate\Translation\MessageSelector $selector
3);

#Example Use

In the following example, we will extend the MessageSelector to return always return the same string when resolving a translation line using the choice and transChoice methods:

1<?php
2 
3use Illuminate\Translation\MessageSelector;
4 
5class MyMessageSelector extends MessageSelector
6{
7 
8 /**
9 * Override the `choose` method to always return
10 * the same translation line.
11 *
12 * @param string $line
13 * @param int $number
14 * @param string $locale
15 * @return string
16 */
17 public function choose($line, $number, $locale)
18 {
19 return 'A static message.';
20 }
21 
22}

Armed with our custom MessageSelector implementation, we can now set it as the MessageSelector to use:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Create a new instance of MyMessageSelector
5$myMessageSelector = new MyMessageSelector;
6 
7// Set the MessageSelector instance.
8$translator->setSelector($myMessageSelector);
9 
10// Ask the translator for any line with the `choice`
11// or `transChoice` methods and we will always
12// get `A static message.` as the result.
13$line = $translator->choice('any.key', 1);

#Working with Translator Locales

The Laravel translator exposes a number of methods that can be used to determine what the current locale configuration is, as well as allow for configuration modification at runtime in response to application conditions.

These methods are fairly straightforward; we will briefly discuss each one in the following sections.

#Setting the Application Locale With setLocale

The setLocale method can be used to set the translator's default locale.

#Signature

The signature of the setLocale method is:

1public function setLocale(
2 $locale
3);

#Example Use

In the following example, we will change the translator's default locale to es:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Change the default locale to `es`.
5$translator->setLocale('es');

#Getting the Application Locale With getLocale

The getLocale method is used to determine what the currently configured default locale is.

#Signature

The signature of the getLocale method is:

1public function getLocale();

#Example Use

For the following example, we will see how the results of calling the getLocale method change after we manipulate the currently configured default locale:

1// Ask the Service Container for a translator instance.
2$translator = app('translator');
3 
4// Get the current default locale.
5$beforeSetLocale = $translator->getLocale();
6 
7// Set a new default locale.
8$translator->setLocale('es');
9 
10// Get the current default locale.
11$afterSetLocale = $translator->getLocale();

After the above code has executed, the locale variables would contain the following values:

Variable Name Value
$beforeSetLocale en
$afterSetLocale es

#Getting the Application Locale With locale

The locale method is an alias of the getLocale and share the same signatures and behavior. They can be used interchangeably.

#Setting the Fallback Locale With setFallback

The Laravel translator supports the concept of a fallback language, or a language that will be used if no translation lines can be found for the current locale. We can use the setFallback method to change this at runtime.

#Signature

The signature of the setFallback method is:

1public function setFallback(
2 $locale
3);

#Example Use

In the following example, we will use the setFallback method to change the current fallback locale to it:

1<?php
2// Ask the Service Container for a translator instance.
3$translator = app('translator');
4 
5// Set the fallback locale to `it`.
6$translator->setFallback('it');

#Getting the Fallback Locale With getFallback

The getFallback method is the logical counterpart to the setFallback method and can be used to determine the currently configured fallback locale.

#Signature

The signature of the getFallback method is:

1<?php
2public function getFallback();

#Example Use

In the following example, we will change the currently configured fallback locale and observe how the fallback locale setting changes as we manipulate it.

1<?php
2// Ask the Service Container for a translator instance.
3$translator = app('translator');
4 
5// Get the current fallback locale.
6$beforeSetFallbackLocale = $translator->getFallback();
7 
8// Set the fallback locale.
9$translator->setFallback('it');
10 
11// Get the current fallback locale.
12$afterSetFallbackLocale = $translator->getFallback();

After the above code has executed, as we might expect, the local variables would contain the following values:

Variable Name Value
$beforeSetFallbackLocale en
$afterSetFallbackLocale it

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.