Laravel 5: The Translator's File Loader

February 19, 2018 —John Koster

The FileLoader is the class that is responsible for loading the translation files from the file system. The language files are loaded from the /resources/lang/ directory by default. The lang/ directory contains the en (English from the ISO 639-1 standard) sub-directory by default. Each sub-directory within the lang/ directory corresponds to a difference locale; the locale should share the same name as the sub-directory.

#PHP Based Language Files

Each locale directory may contain various PHP files returning arrays. These arrays contain a key/value pair, indicating the key of the translation and the value of the language translation. For example, the following is the contents of the /resources/lang/en/passwords.php file:

1<?php
2 
3return [
4 
5 // ...
6 
7 'password' =>
8 'Passwords must be at least six characters and match the
9 confirmation.',
10 'user' => "We can't find a user with that e-mail address.",
11 'token' => 'This password reset token is invalid.',
12 'sent' => 'We have e-mailed your password reset link!',
13 'reset' => 'Your password has been reset!',
14 
15];

The individual PHP files containing the translation lines are referred to as "groups". For a fresh Laravel installation, the following groups exist:

Group Name Path
Authentication resources/lang/en/auth.php
Pagination resources/lang/en/pagination.php
Passwords resources/lang/en/passwords.php
Validation resources/lang/en/validation.php

#JSON Based Language Files

It is also possible to create language files using a JSON object. When creating language files with JSON, we do not create a sub-directory for each locale; rather, we create a JSON file with the locale as its name according to the format <LOCALE_NAME>.json. If we wanted to create a JSON based locale file for Spanish, we could create a es.json language file within the root language file directory (/resources/lang).

When creating these JSON files, each language key/value is stored as a property within the JSON object; translation keys cannot be nested. Because we cannot nest the key names in the JSON language files, if your application makes use of both PHP based language files and JSON language files, you may occasionally run into issues where language keys are not resolved from the JSON files when using dot notation.

However, we can emulate the dot notation syntax that is used to retrieve nested translation strings from PHP-based files by providing the dot notation as part of the JSON key (notice the validation.accepted key):

1{
2 "validation.accepted": "The :attribute must be accepted.",
3 "active_url": "The :attribute is not a valid URL."
4}

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.