Laravel - Localization
Laravel - Localization (L10n)
Section titled “Laravel - Localization (L10n)”Laravel’s localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. Language strings are typically stored in files within the lang directory at the root of your project (prior to Laravel 9, this was resources/lang).
Directory Structure for Language Files
Section titled “Directory Structure for Language Files”Within the lang directory, you should create a subdirectory for each language supported by your application. For example:
/lang /en messages.php validation.php /es messages.php validation.php /fr messages.php validation.php main.json // Example of a JSON translation fileLanguage files can be either PHP files that return an array of keyed strings, or JSON files.
PHP Language Files
Section titled “PHP Language Files”PHP language files return an array of keyed strings. For example, lang/en/messages.php might look like this:
<?php
return [ 'welcome' => 'Welcome to our application!', 'greeting' => 'Hello, :name.', // Placeholder for dynamic data];And lang/es/messages.php (Spanish translation):
<?php
return [ 'welcome' => '¡Bienvenido a nuestra aplicación!', 'greeting' => 'Hola, :name.',];JSON Language Files
Section titled “JSON Language Files”Alternatively, you can define your translation strings in JSON files. For strings that are frequently translated across many files, this can be more convenient. For example, lang/es.json:
{ "I love programming.": "Me encanta programar.", "This is a test string.": "Esta es una cadena de prueba."}Retrieving Translation Strings
Section titled “Retrieving Translation Strings”You can retrieve translation strings using the __ helper function (double underscore) or the @lang Blade directive. The __ function accepts the file and key of the string as its first argument using “dot” notation.
From a PHP file (e.g., controller):
$welcomeMessage = __('messages.welcome'); // Retrieves from messages.php
// For JSON files, just use the key directly:$loveProgramming = __('I love programming.');From a Blade template:
<h1>{{ __('messages.welcome') }}</h1><p>@lang('I love programming.')</p>
<!-- Using placeholders --><p>{{ __('messages.greeting', ['name' => 'John']) }}</p>Pluralization
Section titled “Pluralization”Pluralization is complex, as different languages have a variety of complex rules for pluralization. You can define strings with pluralization options using a “pipe” character to separate singular and plural forms:
'apples' => 'There is one apple|There are :count apples',
// In Blade or PHP:$message = trans_choice('messages.apples', 10); // Output: There are 10 apples$message = trans_choice('messages.apples', 1); // Output: There is one appleThe trans_choice function (or Lang::choice facade method) is used for retrieving these pluralized strings.
Setting the Current Locale
Section titled “Setting the Current Locale”The default language for your application is stored in the config/app.php configuration file in the locale option. You can change the active language at runtime using the App::setLocale method:
use Illuminate\Support\Facades\App;
// Example in a controller method or middlewareApp::setLocale('es'); // Sets the current language to SpanishA common practice is to allow users to select their preferred language, often storing this preference in their session or user profile, and then setting the locale via middleware.
Example: Language Switching Controller
Section titled “Example: Language Switching Controller”Step 1: Ensure you have language files. For example, create lang/en/demo.php and lang/fr/demo.php.
<?php return ['title' => 'Laravel Localization Example']; ?>
// lang/fr/demo.php<?php return ['title' => 'Exemple de localisation Laravel']; ?>Step 2: Create a controller, e.g., LocalizationController (php artisan make:controller LocalizationController).
app/Http/Controllers/LocalizationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;use Illuminate\Support\Facades\App;use Illuminate\Support\Facades\Session; // To store locale in session
class LocalizationController extends Controller{ public function setLocale(Request $request, $locale) { if (in_array($locale, ['en', 'fr', 'es'])) { // Validate locale App::setLocale($locale); Session::put('locale', $locale); // Store it in session return redirect()->back()->with('status', "Language changed to {$locale}!"); } return redirect()->back()->with('error', 'Invalid language selected.'); }
public function showDemoPage() { // Optionally retrieve locale from session if not set by URL parameter yet // if (Session::has('locale')) { // App::setLocale(Session::get('locale')); // } return view('localization_demo'); // We'll create this view }}Step 3: Create a simple Blade view resources/views/localization_demo.blade.php:
<!DOCTYPE html><html><head> <title>@lang('demo.title')</title></head><body> <h1>@lang('demo.title')</h1> <p> Current locale: {{ App::getLocale() }} </p> <p> <a href="{{ url('locale/en') }}">English</a> | <a href="{{ url('locale/fr') }}">Français</a> | <a href="{{ url('locale/es') }}">Español</a> (Add 'es' files for this to work fully) </p>
@if (session('status')) <div style="color: green;">{{ session('status') }}</div> @endif @if (session('error')) <div style="color: red;">{{ session('error') }}</div> @endif</body></html>Step 4: Add routes in routes/web.php:
use App\Http\Controllers\LocalizationController;
Route::get('locale-demo', [LocalizationController::class, 'showDemoPage']);Route::get('locale/{locale}', [LocalizationController::class, 'setLocale']);Step 5: Test by visiting URLs:
http://localhost:8000/locale-demo(will use default or session locale)http://localhost:8000/locale/en(then refreshlocale-demoor navigate to it)http://localhost:8000/locale/fr(then refreshlocale-demoor navigate to it)
You will see the title and status messages change based on the selected language. This example also shows how to store the user’s preferred locale in the session.
Fallback Language: You can also configure a fallback_locale in config/app.php. This language will be used when the active language does not contain a given translation string.
For more advanced localization topics, such as overriding vendor package language files or using short keys, refer to the official Laravel localization documentation.