Most modern international apps require support for at least one language if not more. Laravel supports this out of the box. The concept is called localization. Or in short l10n, 10 is for the number of letters between "l" and "n". Also luckily the implementation is very simple. Let's do it in 3 steps.

1. Create language files

Create language file in the folder resources/lang/en/messages.php for English and /lang/fr/messages.php for the language French. The name of the folder is the name of the language to be used in your application. So if you set the language to "en", the messages will come from the "en" language folder.

/resources
	/lang
    	/en
        	messages.php
       	/fr
        	messages.php

2. Insert a message

Inside resourcs/lang/en/messages.php.

<?php

return [
	"greeting" => "Good morning",
];

And inside resources/lang/fr/messages.php

<?php

return [
	"greeting" => "Bonjour",
];

3. Usage

Anywhere in the application you can now return translated message.

dump(__("messages.greeting"))

<h1>{{__("messages.greeting"))}}</h1>

return view("index",["greeting"=>__("messages.greeting")]);

Done! it was that easy!

Scooter, Perseverance, success, motivation, the end
Photo by Alex Guillaume / Unsplash

Still stuck around? Here is more things you need to know about Laravel localization.

__() is another version of the helper trans()

If we check the definition of the __() function inside src/Illuminate/Foundation/helpers.php   we find the following code:


if (! function_exists('__')) {

    function __($key = null, $replace = [], $locale = null)
    {
        if (is_null($key)) {
            return $key;
        }

        return trans($key, $replace, $locale);
    }
}

This is to say wherever you can use __(), you can use trans(). And you have seen in the function definition, we can also

Replace the variables in strings and set language in the __() function

In the previous example, we can add a name variable in the greeting message, and pass the name dynamically when you want to call the message.

<?php

return [
	"greeting" => "Bonjour :name",
];

Then you call as:

__("messages.greeting",["name"=>"Jane"])

Or with language setting:

__("messages.greeting",["name"=>"Jane"],"en")

Set the language/locale once

You can set the language in your route, as:

use Illuminate\Support\Facades\App;

Route::get('/greeting/{locale}', function ($locale) {
    if (! in_array($locale, ['en', 'fr'])) {
        abort(400);
    }

    App::setLocale($locale);
});

Set fallback language

You can set fallback language if the message is not found in the translation files of the set language. Inside config/app.php add the line

'fallback_locale' => 'en',

And again, it is that easy!