Introduction
Laravel provides built-in support for localization, allowing you to build multilingual applications with ease. This guide will walk you through setting up multi-language support in Laravel.
1. Setting Up Language Files
Laravel stores language files in the resources/lang/
directory. Each language should have its own folder:
resources/lang/
├── en/
│ ├── messages.php
├── fr/
│ ├── messages.php
Create a language file, for example, resources/lang/en/messages.php
:
'Welcome to our application!',
'hello' => 'Hello, :name!'
];
2. Using the __('')
Helper
To display translated content, use the __('')
helper function:
{{ __('messages.welcome') }}
For dynamic values, use placeholders:
{{ __('messages.hello', ['name' => 'John']) }}
3. Changing the Application Language
Laravel determines the language from the configuration file config/app.php
:
'locale' => 'en',
To change the language dynamically:
App::setLocale('fr');
4. Implementing Language Switching
Define a route in routes/web.php
to change the language:
Route::get('lang/{locale}', function ($locale) {
if (in_array($locale, ['en', 'fr'])) {
session(['locale' => $locale]);
}
return redirect()->back();
});
Modify AppServiceProvider.php
to apply the saved language:
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
public function boot()
{
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}
}
5. Adding a Language Switcher in the View
Add the following language switcher to your Blade template:
<a href="{{ url('lang/en') }}">English</a>
<a href="{{ url('lang/fr') }}">Français</a>
6. Translating Validation Messages
Laravel includes default translation files for validation messages in resources/lang/{locale}/validation.php
. You can customize them as needed.
7. Using JSON Translation Files
Instead of PHP arrays, you can use JSON files stored in resources/lang/{locale}.json
:
{
"welcome": "Welcome to our application!",
"hello": "Hello, :name!"
}
Use the __('key')
helper to retrieve translations:
{{ __('welcome') }}
Conclusion
By following these st
0 Comments