Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translation strings as keys in Laravel

I read the documentation for translation strings on Retrieving Translation Strings but somehow I don't understand how to apply it.

Let's say I would like to render in a view posts.index the message "I like programming" in English, German ("Ich mag Programmieren") or Spanish ("Me encanta programar"), depending on the localization set by App::setLocale().

How would the translation files look like and how would I setup the view?

like image 400
Andreas Avatar asked Nov 28 '22 13:11

Andreas


1 Answers

I finally understood the concept. Within resources/lang you create a translation JSON file for every language, e. g.:

/resources
    /lang
        /de.json
        /es.json

There is no need to create an en.json file as en will be the default language if you don't set a language with App::setLocale().

de.json:

{
     "I love programming.": "Ich mag programmieren."
}

es.json:

{
     "I love programming.": "Me encanta programar."
}

Next, you set in your controller the language via App::setLocale(); and now comes the fun part. In the view, you only include the key of the JSON, e. g.

{{ __('I love programming.') }}

and depending on your localization, Laravel will automatically load the correct translation.

like image 188
Andreas Avatar answered Dec 11 '22 12:12

Andreas