What is the purpose of Lang in a Laravel application?

Lang in Laravel is a façade, that provides a convenient way to retrieve strings in various languages, and allows us to easily support multiple languages within an application.

Laravel Localization enables to present an application in multiple languages.

Lang Files

Language strings for multiple languages are stored in files under the resources folder, within the resources/lang directory. Inside this directory we can add subdirectories for each language, which the Laravel application supports.

/resources
    /lang
        /en
            messages.php
        /es
            messages.php

Purpose of a Lang file

Language files return an array of keyed strings. For example:

<?php
 
return [
    'welcome' => 'Welcome to Laravel'
];

Lang in Laravel can retrieve data from language files

The ‘Lang’ keyword can also be used to retrieve data from a language file. Consider the example below.

echo Lang::get('messages.welcome');

The string passed to a get method. First string is name of the language file, i.e. messages.php. While the second is the name of the line we can retrieve from the language file.

If a specific language does not exist. The language key, will return by the get method.

Lang in Laravel can make line replacements

Placeholders for objects returned can be added in using the Lang keyword. For example

'welcome' => 'Welcome, :user',

A second argument can be passed to the Lang::get method as the replacement code.

echo Lang::get('messages.welcome', ['user' => 'Kate']);

This updates the welcome message and directs to the user ‘Kate’. The update is done in the messages.php file for the welcome message returned.

Lang reads if a file has a specific line of code

Lang in Laravel can determine if a language file has a specific string. It can then perform the corresponding action.

if (Lang::has('messages.welcome'))
{
    //
}

As shown above, Lang::has checks if the messages file returns welcome. If so, it can do any action. This feature supports validation. For example, before replacing a block of code, confirming if the object is returned assures that replacement is being made at the right place.

Leave a Comment