To internationalize and localize content in Blade templates for multiple languages in Laravel, you can follow these steps:
Step 1: Install and configure the localization package
composer require mcamara/laravel-localization
config/app.php
file:'providers' => [
// ...
Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,
],
php artisan vendor:publish --tag=laravel-localization
php artisan migrate
Step 2: Set up language files
resources/lang
if it doesn't exist.lang
directory, create a directory for each language you want to support, e.g., en
for English, es
for Spanish, etc.messages.php
file that will contain all the translation strings. For example, resources/lang/en/messages.php
for English and resources/lang/es/messages.php
for Spanish.messages.php
file, define translation strings using an associative array:return [
'welcome' => 'Welcome to our website!',
'home' => 'Home',
];
Step 3: Update routes
routes/web.php
file and add the following code to define the available locales and set the current locale:Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
],
function(){
// Add your routes here
Route::get('/', function () {
return view('welcome');
});
}
);
Step 4: Update views
__()
helper function, passing the translation key as a parameter:<h1>{{ __('welcome') }}</h1>
<a href="#">{{ __('home') }}</a>
Step 5: Generate language selector
@php
$locales = LaravelLocalization::getSupportedLocales();
@endphp
<ul>
@foreach($locales as $localeCode => $properties)
<li>
<a href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
{{ $properties['native'] }}
</a>
</li>
@endforeach
</ul>
Now, when you access your website, Laravel will automatically determine the user's preferred language based on their browser settings and display the content in the respective language. The language selector will also allow users to switch between different available languages.