How to use @lang directive in Laravel blade?

Blade directives are shortcut codes that help to implement basic PHP control structure. For example loop and conditional statements. It helps makes a code snippets clean and easier to understand. @lang directive is one of these.

We can use the @lang directive to display messages from specific languages as part of Laravel Localization. This is one of the Blade features that make the HTML view easier to work with.

The @lang directive helps retrieve translation strings with multi-language support Laravel application.

When using multi language support in a Laravel application to retrieve lines from language files, you may use the __ helper function. This method accepts the file and the key of the translation string as its first argument. For example, to retrieve the welcome translation string from the resources/lang/messages.php language file, you may use the code snippet below.

{{ __('messages.welcome') }}

@lang('messages.welcome')

A Blade templating engine, allows you to use the syntax in line 1 to echo the translation string or use the @lang directive.

The @lang directive is compiled in the Illuminate\View\Compilers\BladeCompiler class.

The BladeCompiler is then registered as a singleton in the Illuminate\View\ViewServiceProvider class. You may then add the newly created provider in the providers array inside config/app.php.

You can find the code logic behind the @lang directive, and even create a customizable version of it.


    'providers' => [
        ...
        Illuminate\View\ViewServiceProvider::class,
        ...
    ],
    ...