LaraflareDocsFrameworkPackagesReleases13.x

Docs / Digging Deeper / Localization

Localization

Introduction

Note

By default, the laraflare application skeleton does not include the lang directory. If you would like to customize laraflare's language files, you may publish them via the lang:publish Artisan command.

laraflare's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.

laraflare provides two ways to manage translation strings. First, language strings may be stored in files within the application's lang directory. Within this directory, there may be subdirectories for each language supported by the application. This is the approach laraflare uses to manage translation strings for built-in features such as validation error messages:

/lang
    /en
        messages.ts
    /es
        messages.ts

Or, translation strings may be defined within JSON files that are placed within the lang directory. When taking this approach, each language supported by your application would have a corresponding JSON file within this directory. This approach is recommended for applications that have a large number of translatable strings:

/lang
    en.json
    es.json

We'll discuss each approach to managing translation strings within this documentation.

Publishing the Language Files

By default, the laraflare application skeleton does not include the lang directory. If you would like to customize laraflare's language files or create your own, you should scaffold the lang directory via the lang:publish Artisan command. The lang:publish command will create the lang directory in your application and publish the default set of language files used by laraflare:

npx artisan lang:publish

Note

A Worker has no folder to read language files from at runtime, so the files are bundled with your application. Besides the language files, lang:publish writes lang/en.json and a lang/index.ts that registers every locale's files with the translator (using registerTranslations), and adds import '../lang'; to bootstrap/app.ts. Run lang:publish --existing after adding a locale or a file to regenerate lang/index.ts.

Configuring the Locale

The default language for your application is stored in the config/app.ts configuration file's locale configuration option, which is typically set using the APP_LOCALE environment variable. You are free to modify this value to suit the needs of your application.

You may also configure a "fallback language", which will be used when the default language does not contain a given translation string. Like the default language, the fallback language is also configured in the config/app.ts configuration file, and its value is typically set using the APP_FALLBACK_LOCALE environment variable.

You may modify the default language for a single HTTP request at runtime using the setLocale method provided by the App facade:

import { abort, App, Route } from '@laraflare/framework';

Route.get('/greeting/{locale}', async (request, locale: string) => {
    if (! ['en', 'es', 'fr'].includes(locale)) {
        abort(400);
    }

    await App.setLocale(locale);

    // ...
});

Note

The locale set with setLocale belongs to the request being handled, since every request on a Worker shares the same configuration.

Determining the Current Locale

You may use the currentLocale and isLocale methods on the App facade to determine the current locale or check if the locale is a given value:

import { App } from '@laraflare/framework';

const locale = App.currentLocale();

if (App.isLocale('en')) {
    // ...
}

Pluralization Language

You may instruct laraflare's "pluralizer", which is used by the framework to convert singular strings to plural strings, to use a language other than English. This may be accomplished by invoking the useLanguage method within the boot method of one of your application's service providers. The pluralizer's currently supported languages are: english and portuguese:

import { Pluralizer } from '@laraflare/framework';

/**
 * Bootstrap any application services.
 */
override boot(): void
{
    Pluralizer.useLanguage('portuguese');

    // ...
}

Warning

If you customize the pluralizer's language, you should explicitly define your model's table names with its static table property.

Defining Translation Strings

Using Short Keys

Typically, translation strings are stored in files within the lang directory. Within this directory, there should be a subdirectory for each language supported by your application. This is the approach laraflare uses to manage translation strings for built-in features such as validation error messages:

/lang
    /en
        messages.ts
    /es
        messages.ts

All language files export an object of keyed strings as their default export. For example:

// lang/en/messages.ts

export default {
    welcome: 'Welcome to our application!',
};

Warning

For languages that differ by territory, you should name the language directories according to the ISO 15897. For example, "en_GB" should be used for British English rather than "en-gb".

Using Translation Strings as Keys

For applications with a large number of translatable strings, defining every string with a "short key" can become confusing when referencing the keys in your screens and it is cumbersome to continually invent keys for every translation string supported by your application.

For this reason, laraflare also provides support for defining translation strings using the "default" translation of the string as the key. Language files that use translation strings as keys are stored as JSON files in the lang directory. For example, if your application has a Spanish translation, you should create a lang/es.json file:

{
    "I love programming.": "Me encanta programar."
}

Key / File Conflicts

You should not define translation string keys that conflict with other translation filenames. For example, translating __('Action') for the "NL" locale while a nl/action.ts file exists but a nl.json file does not exist will result in the translator returning the entire contents of nl/action.ts.

Retrieving Translation Strings

You may retrieve translation strings from your language files using the __ helper function. If you are using "short keys" to define your translation strings, you should pass the file that contains the key and the key itself to the __ function using "dot" syntax. For example, let's retrieve the welcome translation string from the lang/en/messages.ts language file:

import { __ } from '@laraflare/framework';

console.log(__('messages.welcome'));

If the specified translation string does not exist, the __ function will return the translation string key. So, using the example above, the __ function would return messages.welcome if the translation string does not exist.

If you are using your default translation strings as your translation keys, you should pass the default translation of your string to the __ function;

console.log(__('I love programming.'));

Again, if the translation string does not exist, the __ function will return the translation string key that it was given.

The screens of a laraflare application are Vue components (resources/js), so translation strings are retrieved on the server, for example in a controller, and passed to the screen as props.

Replacing Parameters in Translation Strings

If you wish, you may define placeholders in your translation strings. All placeholders are prefixed with a :. For example, you may define a welcome message with a placeholder name:

welcome: 'Welcome, :name',

To replace the placeholders when retrieving a translation string, you may pass an object of replacements as the second argument to the __ function:

console.log(__('messages.welcome', { name: 'dayle' }));

If your placeholder contains all capital letters, or only has its first letter capitalized, the translated value will be capitalized accordingly:

welcome: 'Welcome, :NAME', // Welcome, DAYLE
goodbye: 'Goodbye, :Name', // Goodbye, Dayle

Object Replacement Formatting

If you attempt to provide an object as a translation placeholder, its toString method will be invoked. However, sometimes you may not have control over the toString method of a given class, such as when the class that you are interacting with belongs to a third-party library.

In these cases, laraflare allows you to register a custom formatting handler for that particular type of object. To accomplish this, you should invoke the translator's stringable method. The stringable method accepts the class of object it is responsible for formatting and a closure that formats it. Typically, the stringable method should be invoked within the boot method of your application's AppServiceProvider class:

import { Lang } from '@laraflare/framework';
import { Money } from 'some-money-library';

/**
 * Bootstrap any application services.
 */
override boot(): void
{
    Lang.stringable(Money, (money) => {
        return money.formatTo('en_GB');
    });
}

Pluralization

Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization; however, laraflare can help you translate strings differently based on pluralization rules that you define. Using a | character, you may distinguish singular and plural forms of a string:

apples: 'There is one apple|There are many apples',

Of course, pluralization is also supported when using translation strings as keys:

{
    "There is one apple|There are many apples": "Hay una manzana|Hay muchas manzanas"
}

You may even create more complex pluralization rules which specify translation strings for multiple ranges of values:

apples: '{0} There are none|[1,19] There are some|[20,*] There are many',

After defining a translation string that has pluralization options, you may use the trans_choice function to retrieve the line for a given "count". In this example, since the count is greater than one, the plural form of the translation string is returned:

import { trans_choice } from '@laraflare/framework';

console.log(trans_choice('messages.apples', 10));

You may also define placeholder attributes in pluralization strings. These placeholders may be replaced by passing an object as the third argument to the trans_choice function:

minutes_ago: '{1} :value minute ago|[2,*] :value minutes ago',

console.log(trans_choice('time.minutes_ago', 5, { value: 5 }));

If you would like to display the integer value that was passed to the trans_choice function, you may use the built-in :count placeholder:

apples: '{0} There are none|{1} There is one|[2,*] There are :count',
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.