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/langdirectory. 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
welcomemessage in themessages.phpfile, create a new file namedmessages.phpinside theesdirectory. -
Add translation keys: In each language file, add the same translation keys as in the original language file. For example, in the
messages.phpfile inside theesdirectory, add the following code:return [ 'welcome' => 'Bienvenido a nuestra aplicación!', ]; -
Update
config/app.php: In theconfig/app.phpfile, add the new language directory to thelocalesarray:'locales' => [ 'en' => 'English', 'es' => 'Spanish', ], 'translation' => [ 'files' => [ base_path('resources/lang'), ], ], -
Update
app/Providers/AppServiceProvider.php: In theAppServiceProvider.phpfile, 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.phpfile:Route::get('/change-language/{locale}', 'LanguageController@changeLanguage')->name('changeLanguage'); -
Create LanguageController: Create a new controller named
LanguageControllerand 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/viewsdirectory. For example, create a new file namedlang.blade.phpand 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/esor/change-language/enURLs. Your application should now support multiple languages using i18n and localization.