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:

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:

Or, in Blade:

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.

Liked the article? Maybe you need help with your Laravel project?
Check out my Upwork profile and hire me!

10 thoughts on “Laravel JSON-based Translations with Underscores __() Function

  1. hello again .

    سلام دوستان ، وقت بخیر

    i created json file on resources/lang folder : fa.json

    {
    “test” : ” hi hi hi”,
    “upload” : {
    “success” : ” upload successfully.”,
    },
    }

    now code worked :
    echo __(‘test’)

    but multi index ( children ) not work :
    echo __(‘upload.success’)

    where is the problem from?

  2. Thanks for your article and its very informative in sense of general and fast development.
    You have showed an example of 2 languages English & Spanish, my question is about how to write json code in lang file for 3 or 3+ languages. Thank You

        1. I will be more thankful to you if you make a tutorial on how to select specific columns from 1 table that is the parent and also the tables with with() or has() methods, because these things are very hard to find on documentation. thnx

Leave a Reply

Your email address will not be published. Required fields are marked *