How to internationalize and localize content in Blade templates for multiple languages in Laravel?

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

  1. Install the Laravel localization package using the following command:
composer require mcamara/laravel-localization
  1. Add the service provider to your config/app.php file:
'providers' => [ // ... Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class, ],
  1. Publish the configuration file using the following command:
php artisan vendor:publish --tag=laravel-localization
  1. Migrate the package's table using the following command:
php artisan migrate

Step 2: Set up language files

  1. Create a new directory resources/lang if it doesn't exist.
  2. Inside the lang directory, create a directory for each language you want to support, e.g., en for English, es for Spanish, etc.
  3. Inside each language directory, create a 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.
  4. In each messages.php file, define translation strings using an associative array:
return [ 'welcome' => 'Welcome to our website!', 'home' => 'Home', ];

Step 3: Update routes

  1. Open the 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

  1. Open your Blade templates and replace the text to be translated with the __() helper function, passing the translation key as a parameter:
<h1>{{ __('welcome') }}</h1> <a href="#">{{ __('home') }}</a>

Step 5: Generate language selector

  1. Add the language selector dropdown to your layout file or any other template file where it is needed:
@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.