Laravel has a great helper function underscores (__) that we can use for JSON-based translations. Laravel 5.6 default authentication blade files also make use of underscore helper function. Like this:
{{ __('Register') }}
In previous versions of Laravel, we used to see Register
only. Let’s first see what it does.
It’s not required to have a project that supports multiple languages using laravel localization to use this function. If you are not interested in localization or multi-language support, leave it as it is and it will work the same way without the underscore function. If you do not have any localization set up, it will return the same string passed as the parameter to the function.
This function was released back in laravel 5.4 to support JSON-based translations.
If you are developing a multi-language project, defining every string with a short key starts to can make things really confusing. Basically, it’s better to use the default translation of the string as the key. They are stored as JSON in the resources/lang
directory. So, if your project supports French language, you can create a resources/lang/fr.json
and define your translations.
{ "Validation Failed": "Validation échouée" }
This allows you to call __(“Validation Failed”) wherever you need. You can also use the @lang directive as well.
@lang("Validation Failed")
If that key is not present, it will return the default language functionality.
Read more about Localization from official documentation:
Learn how to create custom helper functions in Laravel.