Laravel 5: String Translation Public API

Laravel 5: String Translation Public API

Laravel 5

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:

public function get(
    $key,
    array $replace = [],
    $locale = null,
    $fallback = true
);

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):

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Retrieve the validation.accepted translation line.
$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:

// As the Service Container for a translator instance.
$translator = app('translator');

// Ask the translator for a translation line
// that we know does not exist.
$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:

<?php

return [

    // ...

    'accepted'  => 'The :attribute must be accepted.',
    'array'     => 'The :attribute must be an array.',

    // ...

];

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.

// Ask the Service Container for a translator instance.
$translator = app('translator');

// The :attribute must be an array.
$translator->get('validation.array');

// The provided value must be an array.
$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.

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:

<?php

return [

    'accepted' => 'Los :attribute deben ser aceptados.',

];

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

// As the Service Container for a translator instance.
$translator = app('translator');

// Retrieve the validation.accepted translation line.
$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:

// As the Service Container for a translator instance.
$translator = app('translator');

// Retrieve the validation.array translation line.
$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:

// As the Service Container for a translator instance.
$translator = app('translator');

// Retrieve the validation.array translation line.
$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:

public function getFromJson(
    $key,
    array $replace = [],
    $locale = null
);

Example Use

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

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

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

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Retrieve our example message. The returned value will be:
// The :attribute is required, resolved from our example JSON file.
$line = $translator->getFromJson('validation.accepted',
                                 [], 'example');

// Retrieve example with replacements. The returned value will be:
// The name is required, resolved from our example JSON file.
$replacementLine = $translator->getFromJson('validation.accepted', [
        'attribute' => 'name'
    ], 'example');

// Attempt to retrieve a translation line that we have not
// defined in our JSON-based language file. The result is:
// The :attribute must be an array.
$fallbackBehavior = $translator->getFromJson('validation.array',
                                             [], '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

public function trans(
    $key,
    array $replace = [],
    $locale = null
);

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:

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Retrieve the validation.accepted translation line.
$getLine   = $translator->get('validation.accepted');
$transLine = $translator->trans('validation.accepted');

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

// Ask the Service Container for a translator instance.
$translator = app('translator');

// The :attribute must be an array.
$translator->get('validation.array');

$translator->trans('validation.array');

// The provided value must be an array.
$translator->get('validation.array', [
        'attribute' => 'provided value'
    ]);

$translator->trans('validation.array', [
        'attribute' => 'provided value'
    ]);

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:

<?php

return [

    'accepted' => 'Los :attribute deben ser aceptados.',

];

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

// As the Service Container for a translator instance.
$translator = app('translator');

// Retrieve the validation.accepted translation line.
$line      = $translator->get('validation.accepted', [], 'es');
$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:


public function has( $key, $locale = null, $fallback = true );

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.

// Get a translator instance from the Service Container.
$translator = app('translator');

// true
$exists = $translator->has('passwords.reset');

// true
$exists = $translator->has('passwords.reset', 'en');

// true
$exists = $translator->has('passwords.reset', 'es');

// false
$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:

// Get a translator instance from the Service Container.
$translator = app('translator');

// Set the fallback locale.
$translator->setFallback('es');

// false
$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:

// Get a translator instance from the Service Container.
$translator = app('translator');

// Indicate to the translation service that we do not
// want to look at the fallback locale when checking
// if a translation line has been defined.
$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. It's 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

public function hasForLocale(
    $key,
    $locale = null
);

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:

<?php

return [

    // ...

    'accepted'     => 'The :attribute must be accepted.',
    'active_url'   => 'The :attribute is not a valid URL.',

];

resources/lang/es/validation.php:

<?php

return [

    'accepted'     => 'Los :attribute deben ser aceptados.',

];
// Get a translator instance from the Service Container.
$translator = app('translator');

// true
$exists = $translator->hasForLocale('validation.accepted');

// true
$exists = $translator->hasForLocale('validation.accepted', 'es');

// false
$exists = $translator->hasForLocale('validation.active_url', 'es');

// false
$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:

public function choice (
    $key,
    $number,
    array $replace = [],
    $locale = null
);

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:

<?php

return [

    'messages'             => 'You have one unread message.
                              |You have unread messages.',

    'messages_attributes'  => 'You have one unread message.
                              |You have :count unread messages.',

    'messages_with_zero'   => '{0}   You\'re all caught up!
                              |[1]   You have on unread message.
                              |[2,*] You have :count unread messages'
];

I've formatted the localization messages onto multiple lines for readability. If you choose to do this, be aware that the 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:

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Get the translation for one item.
$messageSingle = $translator->choice('plural.messages', 1);

// Get the translation for many items.
$messageMany   = $translator->choice('plural.messages', 2);

// Get the translation for one item.
$messageAttributesSingle = $translator->choice(
                            'plural.messages_attributes',
                            1
                        );

// Get the translation for two items, with attribute replacement.
$messageAttributesMany   = $translator->choice(
                            'plural.messages_attributes',
                            2, [
                                'count' => 2
                            ]
                        );

// Get the translation for a collection with no items.
$messagesWithZero = $translator->choice(
                            'plural.messages_with_zero',
                            0
                        );

// Get the translation for a collection with one item.
$messagesWithZeroSingle = $translator->choice(
                            'plural.messages_with_zero',
                            1
                        );

// Get the translation for a collection of two
// items with attribute replacement.
$messagesWithZeroMany  = $translator->choice(
                            'plural.messages_with_zero',
                            2, [
                                'count' => 2
                            ]
                        );

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:

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Create our sample messages array.
$messages = [
    'Welcome to our service...',
    'Thank you!',
    'Another example message...',
];

// Call the choice method by passing in our messages array.
$countableExample = $translator->choice(
        'plural.messages_with_zero',
        $messages, [
            'count' => count($messages),
        ]
    );

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:

<?php

return [

    'messages' => 'no hay mensajes nuevos
                   |Tienes mensajes no leídos',

];

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

<?php
// Ask the Service Container for a new translator instance.
$translator = app('translator');

// Create our sample messages collection.
$messages = collect([
    'Welcome to our service...',
    'Thank you!',
    'Another example message',
]);

$localeExampleSingle = $translator->choice(
        'plural.messages', 1, [], 'es'
    );

$localeExampleMultiple = $translator->choice(
        'plural.messages', $messages, [], 'es'
    );

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 The FileLoad Public API chapter.

Signature

The signature for the load method is:

public function load(
    $namespace,
    $group,
    $locale
);

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 it's 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:

public 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 The FileLoad Public API chapter.

Signature

The signature of the addNamespace method is:

public function addNamespace(
    $namespace,
    $hint
);

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 The FileLoad Public API chapter.

Signature

The signature of the addJsonPath method is:

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

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:

public function addLines(
    array $lines,
    $locale,
    $namespace = '*'
);

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.

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Get a translation line before calling addLines.
$beforeAddLinesCall = $translator->get(
                    'addlines.test'
                );

// Add a new translation line to the translator.
$translator->addLines([
            'addlines.test' => 'A new line',
        ], 'en'
    );

// Get a translation line after calling addLines.
$afterAddLinesCall = $translator->get(
                    'addlines.test'
                );

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:

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Get the current locale.
$currentLocale = $translator->getLocale();

// Add a new translation to the translator.
$translator->addLines([
        'addlines.test' => 'A new line',
    ], $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:

public function parseKey(
    $key
);

Example Use

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

$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:

$namespaceParts = $translator->parseKey(
            'namespace::passwords.reset',
        );
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:

public function getSelector();

Example Use

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

<?php
// Ask the Service Container for a translator instance.
$translator = app('translator');

// Get the current MessageSelector
$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:

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

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:

<?php

use Illuminate\Translation\MessageSelector;

class MyMessageSelector extends MessageSelector
{

    /**
     * Override the `choose` method to always return
     * the same translation line.
     *
     * @param  string $line
     * @param  int    $number
     * @param  string $locale
     * @return string
     */
    public function choose($line, $number, $locale)
    {
        return 'A static message.';
    }

}

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

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Create a new instance of MyMessageSelector
$myMessageSelector = new MyMessageSelector;

// Set the MessageSelector instance.
$translator->setSelector($myMessageSelector);

// Ask the translator for any line with the `choice`
// or `transChoice` methods and we will always
// get `A static message.` as the result.
$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:

public function setLocale(
    $locale
);

Example Use

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

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Change the default locale to `es`.
$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:

public 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:

// Ask the Service Container for a translator instance.
$translator = app('translator');

// Get the current default locale.
$beforeSetLocale = $translator->getLocale();

// Set a new default locale.
$translator->setLocale('es');

// Get the current default locale.
$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:

public function setFallback(
    $locale
);

Example Use

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

<?php
// Ask the Service Container for a translator instance.
$translator = app('translator');

// Set the fallback locale to `it`.
$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:

<?php
public 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.

<?php
// Ask the Service Container for a translator instance.
$translator = app('translator');

// Get the current fallback locale.
$beforeSetFallbackLocale = $translator->getFallback();

// Set the fallback locale.
$translator->setFallback('it');

// Get the current fallback locale.
$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

Start the Discussion

Leave a comment

Subscribe to our newsletter