Laravel JSON-based Translations with Underscores __() Function

Not sure if you've noticed, but Laravel 5.6 make:auth is generating Blade files with translation-ready texts, so instead of just "Login" you will see {{ __('Login') }}. How does it work and what's the reason? First, if you don't need your project to be multi-language, just leave it as it is, it will just work "by magic", converting whatever string inside __() into the same string itself. Now, let's dig a little deeper. This __() function actually isn't new, it was released in Laravel 5.4 to support JSON-based translations. We're probably all used to have language files in resources/lang/en/ folder, creating files for each substantial section of your app. But the problem is that it's hard to maintain and come up with new array keys like 'error_someone_can_hack_into_the_system', write them all with underscores and also prevent their duplications. So there's a (maybe) better way - to have one JSON file with keys being any actual texts in main language. Example from official documentation - resources/lang/es.json file for Spanish:
{
    "I love programming.": "Me encanta programar."
}
This allows you to call __('I love programming') wherever you need (Controllers, Blade files etc.). The best part is that you can use this function in the same way as before with @lang or trans() functions. In case that the key is not present in JSON (or JSON file missing at all), it will still fallback to the default language functionality. So you can do both:
echo __('messages.welcome');
echo __('I love programming.');
Or, in Blade:
{{ __('messages.welcome') }}
Read more about localization and translations in the official documentation. You may also be interested in our article 10 Best Laravel packages for multi-language projects.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 57 courses (1055 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials