Multilingualism in Laravel 11: How to create a multilingual application in Laravel 11 using i18n and localization?
To create a multilingual application in Laravel 11 using i18n and localization, follow the steps below:
-
Install Laravel 11: First, make sure you have Laravel installed on your system. If not, follow the official Laravel installation guide to install it.
-
Create a new language directory: Create a new directory for your language files in the
resources/lang
directory. For example, if you want to add support for Spanish, create a new directory namedes
. -
Create language files: Inside the new language directory, create new files for each file you want to translate. For example, if you want to translate the
welcome
message in themessages.php
file, create a new file namedmessages.php
inside thees
directory. -
Add translation keys: In each language file, add the same translation keys as in the original language file. For example, in the
messages.php
file inside thees
directory, add the following code:return [ 'welcome' => 'Bienvenido a nuestra aplicaciĆ³n!', ];
-
Update
config/app.php
: In theconfig/app.php
file, add the new language directory to thelocales
array:'locales' => [ 'en' => 'English', 'es' => 'Spanish', ], 'translation' => [ 'files' => [ base_path('resources/lang'), ], ],
-
Update
app/Providers/AppServiceProvider.php
: In theAppServiceProvider.php
file, add the following code to theboot()
method to set the default language:use Illuminate\Support\Facades\App; public function boot() { App::setLocale('en'); // Set the default language to English }
-
Create routes for language switching: Create routes for language switching in your
routes/web.php
file:Route::get('/change-language/{locale}', 'LanguageController@changeLanguage')->name('changeLanguage');
-
Create LanguageController: Create a new controller named
LanguageController
and add the following code to it:namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; class LanguageController extends Controller { public function changeLanguage(Request $request) { App::setLocale($request->locale); return redirect()->back(); } }
-
Create views for language switching: Create views for language switching in your
resources/views
directory. For example, create a new file namedlang.blade.php
and add the following code to it:<ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link {{ App::getLocale() === 'en' ? 'active' : '' }}" href="{{ route('changeLanguage', ['locale' => 'en']) }}">English</a> </li> <li class="nav-item"> <a class="nav-link {{ App::getLocale() === 'es' ? 'active' : '' }}" href="{{ route('changeLanguage', ['locale' => 'es']) }}">EspaƱol</a> </li> </ul>
-
Test your application: Start your Laravel application and test the language switching functionality by visiting the
/change-language/es
or/change-language/en
URLs. Your application should now support multiple languages using i18n and localization.