In the previous chapters, we looked at what an international application is and the different things to consider when building one. We got started with the tour guide application and made the backend of our laravel application.
In this chapter, we will look at how to add support for multiple languages on our application.
Here are the part 1 and part 2 in case you missed it!
Read and followed the previous guides.
The first thing we need to do is to confirm where a user is coming from or the language the user's browser is requesting. If a user requests a specific language URL, we need to give preference to that, else we give preference to the language a users browser is requesting. We will need to set up a middleware to do this check for us.
The next thing is to serve the user content based on this language. We can use a route group if we want to have separate pages for these content. If we want to maintain the same page structure, we can then pass the language as a parameter to our methods. With the language passed, we can retrieve the data from the database.
We can choose to store the data in JSON format or have database table fields for each language. JSON is ideal so we can always add new language without having to adjust our database. We finally need to map strings for things like error messages. We can display the appropriate string based on the language we set.
We will store descriptions as JSON string. The language will serve as the object key while the content as the object value. It should look like this when stored:
1'{ 2 "en" : "This is the English version", 3 "fr" : "C'est la version française", 4 "de" : "Dies ist die deutsche Version." 5 }'
To create a JSON object in PHP, we need to create an array and encode the array as JSON. This can be done using json_encode($array)
. Instead of using json_encode
every time we want to store a destination record, we can define a mutator on the Destination
model to automatically convert our array into objects.
Open ./app/Destination.php
and add the following:
1// app/Destination.php 2 3 [...] 4 class Destination extends Model 5 { 6 protected $casts = [ 7 'description' => 'array' 8 ]; 9 10 [...] 11 12 public function setDescriptionAttribute($value) 13 { 14 $this->attributes['description'] = json_encode($value); 15 } 16 }
We cast description field as an array so that when we retrieve a destination record, we do not have to use
json_decode
on it to retrieve the data. PHP does not have a native way of working with JSON objects. To use a JSON object, we have to convert the object to an array first.
Now, let us store some destinations in the three languages we support. We are going to use a database seeder to store the content in the database.
Run the following command to create a database seeder:
$ php artisan make:seed DestinationTableSeeder
Then, open the database/seeds/DestinationTableSeeder.php
file and replace with the following:
1// database/seeds/DestinationTableSeeder.php 2 <?php 3 4 use Illuminate\Database\Seeder; 5 use App\Destination; 6 7 class DestinationTableSeeder extends Seeder 8 { 9 public function run() 10 { 11 $destinations = [ 12 [ 13 'name' => "New York City", 14 'image' => "https://images.pexels.com/photos/700974/pexels-photo-700974.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", 15 'location' => "United States", 16 'description' =>[ 17 "en" => "This is New York City", 18 "fr" => "C'est New York", 19 "de" => "Dies ist New York" 20 ] 21 ], 22 [ 23 'name' => "Eiffel Tower", 24 'image' => "https://images.pexels.com/photos/5463/people-eiffel-tower-france-landmark.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", 25 'location' => "United States", 26 'description' => [ 27 "en" => "This is the Eiffel Tower", 28 "fr" => "C'est la tour Eiffel.", 29 "de" => "Das ist der Eiffelturm." 30 ] 31 ] 32 ]; 33 34 foreach ($destinations as $destination) { 35 Destination::create($destination); 36 } 37 } 38 }
To run the seeder, use the following command:
$ php artisan db:seed --class=DestinationTableSeeder
We have created the content needed for our destination page. We will look at how to retrieve the content shortly.
Getting the preferred language from a user’s browser is easy. Laravel Request
provides a method for getting it. You can pass an array of languages your application supports, and the method will return a match for it. For example, if the user wants en_US
and your application only has general English en
, the method will return en
, which is convenient for us.
Another cool thing about this method is that, if the user’s preferred language does not exist in our array, the method returns the first item in our array. So you may want to order the languages you support with some preference.
We will make a middleware that will run with the web middleware group. It will set the language of our Laravel application based on the user's browser preference. To create the middleware, run the following command:
$ php artisan make:middleware Localize
Now, open ./app/Http/Controllers/Middleware/Localize.php
and replace with the following:
1<?php 2 3 namespace App\Http\Middleware; 4 5 use Closure; 6 7 class Localize 8 { 9 public function handle($request, Closure $next) 10 { 11 app()->setLocale($request->getPreferredLanguage(config('app.languages'))); 12 return $next($request); 13 } 14 }
This sets the app language based on the famous Request
method we have been talking about. We will define our languages inside ./config/app.php
file.
Navigate to ./config/app.php
and add the following:
1// config/app.php 2 [...] 3 4 'fallback_locale' => 'en', 5 6 'languages' => ['fr','de','en'], 7 8 [...]
Finally, load the middleware in .app/Http/Kernel.php
:
1// app/Http/Kernel.php 2 3 [...] 4 protected $middlewareGroups = [ 5 'web' => [ 6 [...] 7 \App\Http\Middleware\VerifyCsrfToken::class, 8 \Illuminate\Routing\Middleware\SubstituteBindings::class, 9 \App\Http\Middleware\Localize::class, 10 ], 11 [...] 12 ];
Depending on how you intend to compose your routes, setting the app language should not be difficult. For this tour guide, we are going to use route prefixes. These prefixes will represent each of the languages we support. When a user visits the route, we will set the language based on what prefixes it.
Using route prefixes can present a little challenge. Since we want some specific routes to have different language versions, we may need to create different prefixes representing those languages and create the same routes under the prefix group. This is what I mean:
1Route::prefix('en')->group(function() { 2 Route::get('/', function () { return view('welcome'); }); 3 }); 4 Route::prefix('fr')->group(function() { 5 Route::get('/', function () { return view('welcome'); }); 6 }); 7 Route::prefix('de')->group(function() { 8 Route::get('/', function () { return view('welcome'); }); 9 });
That approach does not look good. Instead, We might want to use wildcards on the routes like
Route::get('{lang}/', function () { return view('welcome'); });
and have our controller check the value of the wildcard, but that is equally not efficient.
So, we will use a wildcard prefix instead. Open your routes/web.php
and add the following:
1// routes/web.php 2 [...] 3 Route::prefix('{lang}')->group(function() { 4 // routes here 5 });
Then, we are going to bind this wildcard in our RouteServiceProvider
so we can pick the value of the wildcard. We will also throw a 404 not found
if the wildcard is not part of the languages we support.
Open ./app/Providers/RouteServiceProdiver.php
and add the following:
1// app/Providers/RouteServiceProdiver.php 2 [...] 3 public function boot() 4 { 5 parent::boot(); 6 Route::bind('lang',function ($name){ 7 in_array($name,config('app.languages'))? app()->setlocale($name) : abort(404); 8 }); 9 } 10 [...]
Because we used this approach, any route a user visits will always set the app language. This way, the users have control over the content they see.
For pages with static content, we can use a string map for it. We can then use the app language to determine which content to show our users.
We have looked at the two ways in which we can set the language of our application. Now, let us return the description of our destinations based on the app language.
We can define an accessor on the Destination
model that will return the description we want. However, we cannot define the accessor on the description
attribute itself. If we do, we will no longer be able to retrieve the original JSON string we saved once we choose to update it.
We will define an appended attribute on the model and define an accessor on it. Open the Destination
model and add the following:
1[...] 2 3 class Destination extends Model 4 { 5 [...] 6 7 protected $appends = ['translated_description']; 8 9 [...] 10 11 public function getTranslatedDescriptionAttribute() 12 { 13 return $this->description[app()->getLocale()]; 14 } 15 }
Now, whenever we want to use the translated content (like in our views), we use translated_description
.
Laravel provides a localization feature that makes retrieving strings in various languages easy. To create string maps, we need to create a JSON file named after the language we want to map. The JSON object key will be the primary language version of the string/phrase (in our case, English) and the value will be in the language we want to map.
In our case, we will create fr.json
and de.json
. The string map below will work with the authentication pages generated when we use artisan to make the auth scaffolding.
Next, we will create two files in the resources/lang
to store our string maps
1$ touch resources/lang/fr.json 2 $ touch resources/lang/de.json
Insert the following content into fr.json
file located at resources/lang/fr.json
:
1{ 2 "Login" : "Se connecter", 3 "Password" : "Mot de passe", 4 "E-Mail Address" : "La Adresse électronique", 5 "Forgot Your Password?" : "Mot de passe Oublié?", 6 "Remember Me" : "Souviens-toi de Moi", 7 "Register" : "Enregistrer", 8 "Confirm Password" : "Confirmer Mot de passe", 9 "Name" : "Nom", 10 "Welcome to the TourGuide" : "Bienvenue au TourGuide", 11 "View destinations" : "Voir les destinations", 12 "View More" : "Afficher plus", 13 "Book Now" : "Reserve maintenant", 14 "Phone" : "Téléphone", 15 "Country" : "Votre Pays", 16 "You do not have any reservations" : "Vous n'avez aucune réservation", 17 "How many people are coming?" : "Combien de personnes viennent?", 18 "e.g" : "par exemple", 19 "When would you like to visit?" : "Quand voudriez vous visiter?", 20 "Make a booking" : "Faire une réservation", 21 "Number of tourists" : "Nombre de touristes", 22 "Tour date" : "Date de la tournée" 23 }
Insert the following content into de.json
file located at resources/lang/de.json
:
1{ 2 "Login" : "Anmeldung", 3 "Password" : "Passwort", 4 "E-Mail Address" : "E-Mail-Addresse", 5 "Forgot Your Password?" : "Haben Sie Ihr Passwort vergessen?", 6 "Remember Me" : "Erinnere dich an mich", 7 "Register" : "Registrieren", 8 "Confirm Password" : "Bestätige das Passwort", 9 "Name" : "Name", 10 "Welcome to the TourGuide" : "Willkommen beim TourGuide", 11 "View destinations" : "Ziele anzeigen", 12 "View More" : "Mehr sehen", 13 "Book Now" : "buchen Sie jetzt", 14 "Phone" : "Telefon", 15 "Country" : "Land", 16 "You do not have any reservations" : "Sie haben keine Reservierungen", 17 "How many people are coming?" : "Wie viele Leute werden kommen?", 18 "e.g" : "z.B.", 19 "When would you like to visit?" : "Wann möchten Sie besuchen?", 20 "Make a booking" : "Reservieren", 21 "Number of tourists" : "Anzahl der Touristen", 22 "Tour date" : "Tourdatum" 23 }
Now, let us make use of this in our view file. Open the resources/views/welcome.blade.php
file and edit:
1<!doctype html> 2 <html lang="{{ app()->getLocale() }}"> 3 [...] 4 <body> 5 <div class="flex-center position-ref full-height"> 6 @if (Route::has('login')) 7 <div class="top-right links"> 8 @auth 9 <a href="{{ url('/home') }}">Home</a> 10 @else 11 <a href="{{ route('login') }}">{{ __('Login') }}</a> 12 <a href="{{ route('register') }}">{{ __('Register') }}</a> 13 @endauth 14 </div> 15 @endif 16 17 <div class="content"> 18 <div class="title m-b-md"> 19 {{ __('Welcome to the TourGuide') }} 20 </div> 21 22 <div class="links"> 23 <a href="{{url(app()->getLocale().'/destinations')}}">{{__('View destinations')}}</a> 24 </div> 25 </div> 26 </div> 27 </body> 28 </html>
Using the mapped string is quite easy. In the blade file, use __('String to translate')
. If Laravel cannot find the JSON file for the app-local language, it will use the original string we wish to translate. So, the String to translate
can be in the primary language of our application.
That is all we need do to use the string map.
Laravel uses language strings for errors and validation. These language strings are stored in PHP files within the resources/lang
directory. Within this directory, we need to create subdirectories for each language supported by the application.
Create the following subdirectories – fr
and de
inside resources/lang
.
1$ mkdir resources/lang/fr 2 $ mkdir resources/lang/de
In the two directories we just created, create the following files:
1$ touch resources/lang/fr/auth.php 2 $ touch resources/lang/fr/pagination.php 3 $ touch resources/lang/fr/passwords.php 4 $ touch resources/lang/fr/validation.php 5 $ touch resources/lang/de/auth.php 6 $ touch resources/lang/de/pagination.php 7 $ touch resources/lang/de/passwords.php 8 $ touch resources/lang/de/validation.php
At this stage, head over to the GitHub repository for this project and copy out the required language files.
Now, you can try it out by checking out the login or register pages. Run php artisan serve
then visit the URL.
To see the pages in different language versions, change the language settings on your browser language settings. If you are on a chrome browser, read about how to change your language here.
We have come very far. We have understood what internationalization requires and we created a basic application setup for it. We looked at how to store content in our database when it has multiple language versions. We also looked at how to get the language preference of a user and how to use the app language to show the content we want.
We can say at this point that we fully understand what it takes to build an international application. In the next chapter, we will look at the frontend of the application and make pages to test everything we have built. We will address any accessibility issues that may arise and see how best to make the experience of our application seamless.
The source code to the application in this article is available on GitHub.