Laravel 10 - Localization
Laravel 10 - Localization
In this tutorial, we'll implement localization in Laravel to enable multi-language support for your website, enhancing accessibility and user experience across diverse audiences.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide takes you through the steps to implement multi-language support in a Laravel 10 project. You'll start by setting up a fresh Laravel project, followed by installing the necessary dependencies and the mcamara/laravel-localization package. After configuring the localization settings and publishing the language files, you’ll register middleware for localization and define a route group for handling multiple languages. The guide also walks you through updating the view with language toggle functionality. By the end, you’ll have a multilingual Laravel application where users can switch between languages like English and Spanish dynamically. This setup forms a strong foundation for building fully localized applications in Laravel 10.
Step # 1 : Set Up a Fresh Laravel Project.
Begin by creating a new Laravel project called localization. You can do this using either the Laravel installer or Composer. If you have Laravel installed globally, use the following command.
laravel new localization
Alternatively, if you're using Composer, run.
composer create-project laravel/laravel --prefer-dist localization
These commands will generate a fresh Laravel project named localization, with all the default files and configurations necessary to get started with development.
Step # 2 : Access the Project Directory.
Open a terminal (e.g., Git Bash) and navigate to the root folder of your Laravel project.
cd c:xampp/htdocs/localization
Next, install the necessary dependencies and start the Laravel Vite development server to compile front-end assets by running.
npm install && npm run dev
In a new terminal window or tab (while keeping the Vite server running), navigate to the same project directory to execute additional Laravel commands.
Step # 3 : Install the Localization Package.
To enable localization functionality in your Laravel project, install the mcamara/laravel-localization package by running the following command.
composer require mcamara/laravel-localization
This package provides a set of tools to handle multi-language support, including URL localization and language switching, making it easy to create a multi-lingual application.
Step # 4 : Publish the Localization Configuration.
To publish the localization configuration, run the following command.
php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"
This will generate a new configuration file named laravellocalization.php in the config directory of your Laravel project. The file contains a list of supported languages. To enable specific languages, simply uncomment the ones you want to support. For this setup, we’ll go with the default options, English and Spanish, which are already uncommented.
Step # 5 : Register Middleware.
Next, open App\Http\Kernel.php and add the following lines to the protected $middlewareAliases array.
/**** OTHER MIDDLEWARE ****/
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class,
This will register the necessary middleware to handle localization routes, redirects, session handling, cookies, and view paths for your application.
Step # 6 : Define Localized Route Group.
To enable localization for specific routes, you need to define a route group with localization settings. Add the following code to your routes/web.php file.
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function() {
Route::get('/', function() {
return view('welcome');
});
/** Add other localized routes here **/
});
/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
This route group will apply the necessary middleware for session redirects, localization redirects, and view paths to all routes inside the group. You can add your localized routes within this group to handle different languages for the pages.
Step # 7 : Update View.
For testing purposes, replace the content of the welcome.blade.php file with the following HTML code. This will include localization support and a language toggle feature.
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>Localization - Code Shotcut</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/starter-template/">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<!--The {{ __('msg.site') }} will display the localized text for the site key from your language files -->
<a class="navbar-brand" href="#">{{ __('msg.site') }}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">{{ __('msg.home') }}<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">{{ __('msg.about') }}<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ __('msg.language') }}</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<!-- We will change the language based on the user selection -->
<a class="dropdown-item" href="{{ url('/en') }}">En (English)</a>
<a class="dropdown-item" href="{{ url('/es') }}">Es (Spanish)</a>
</div>
</li>
</ul>
</div>
</nav>
<main role="main" class="container mt-5">
<div class="row">
<div class="starter-template">
<h1>Bootstrap starter template</h1>
<p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
</div>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
This code provides the structure for your view, including language selection functionality that dynamically changes the language of the site based on the user's choice. The __('msg.site'), __('msg.home'), and other such keys will be replaced with the appropriate localized values from your language files.
Step # 8 : Publish Language Files for Multi-Language Support.
To enable multi-language support, run the following command.
php artisan lang:publish
This will generate a lang folder inside the app directory. By default, the lang folder will contain an /en folder. To add support for Spanish (es), create an /es folder within the lang directory. Your directory structure should look like this.
Next, create a msg.php file inside both the lang/en and lang/es folders. The contents of these files will contain the respective translations.
lang/en/msg.php:
<?php
return [
'site' => 'All About Laravel',
'home' => 'Home',
'about' => 'About',
'language' => 'Language',
// Add translations for any other words or phrases
];
lang/es/msg.php:
<?php
return [
'site' => 'Todo sobre Laravel',
'home' => 'Hogar',
'about' => 'Acerca de',
'language' => 'Idioma',
// Add translations for any other words or phrases
];
Step # 9 : It's time to test.
Now that the language files are in place, it's time to test the language switching functionality. Start the Laravel development server.
php artisan serve
Open the following URL in your browser: http://127.0.0.1:8000. By default, the language will be set to English.
To change the language, use the dropdown menu in the navbar to select a different language (such as Spanish).
This will dynamically update the language content on the page.
Conclusion
By following this guide, you’ve successfully set up multi-language support in your Laravel 10 project using the mcamara/laravel-localization package. Your application now allows users to switch between languages like English and Spanish, creating a more accessible experience. With this foundation in place, you can easily add additional languages by updating your language files and routes. The laravel-localization package simplifies managing multi-language content and can be extended to include other features, such as region-specific content and translations. As your application grows, you can continue to enhance it with more advanced localization strategies.
For more details please refer to official mcamara/laravel-localization package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments