Learning Management Platform for Written Tutorial Series.

Laravel 5 Localization

Laravel 5 Localization

Introduction

Laravel Localization allows our application to adapt to the needs of a particular user’s language, cultural look and feel. For example, a Spanish speaking user might want the system to be displayed in Spanish while an English-speaking user might prefer to use English as the language for the application.

In this tutorial, we are going to look at how we can provide a solution that meets the needs of both users. Laravel supports localization out of the box. However, we will also look at external packages that simplify working with localization.

By the end of this tutorial, you would have known how to create an application that is capable of switching between different locales.

The following screen shots show you what you will build by the end of this tutorial. The first screen shot is in English while the second screen shot is in Spanish.

Laravel Localization en

Laravel Localization es

Topics to be covered

In this tutorial, we will cover the following topics

  • Tutorial prerequisites
  • Tutorial starter code
  • Localization basics
  • Laravel localization packages
    • Laravel Localization
    • Laravel Langman
  • Localization Larashop Admin Panel
  • Complete Tutorial Code

Tutorial prerequisites

This tutorial assumes;

  • You understand the basics of Laravel 5. If you do then I recommend you start with these Laravel 5 Tutorial series.
  • You have PHP, MySQL and a web server i.e. Apache up and running
  • Laravel Homestead – this is optional but provides a great development environment. If you are new to Laravel homestead then I recommend you read the series on Laravel Homestead
  • You have composer installed
  • You have a text editor or IDE that supports PHP.
  • You have a modern web browser that supports HTML5
  • Git – this is optional but highly recommended. This tutorial has a repository on GitHub, with Git, you will be able to clone starter code for each tutorial.

Tutorial starter code

This tutorial builds on from the previous tutorial. If you have not been following the tutorial series, then you can download starter code for this tutorial from GitHub

If you have git installed, run the following command to clone the project

git clone -b 07_user_roles_and_permissions https://github.com/KodeBlog/Laradmin.git laradmin

HERE,

  • git clone -b 07_user_roles_and_permissions clones the branch 07_user_roles_and_permissions from the repository https://github.com/KodeBlog/Laradmin.git into a local folder laradmin.

Localization basics

When we converted the HTML template into Laravel blade views, we hard-coded the text that describes the various properties of our admin panel.

In this tutorial, we will take advantage of the blade localization directive to replace the hard-coded text with what we will define in the language files.

The language files should be created in /resources/lang/locale i.e. for English language, the language files should be in /resouces/lang/en while for Spanish should be in /resources/lang/es.

Let’s take a look resources directory

Laravel Localization en

As you can see from the above image, Laravel uses en as the default locale and comes with a number of default files.

  • resources/lang/en/auth.php – contains the English language translations that are used for authentication messages
  • resources/lang/en/pagination.php – contains the English language translations used for Eloquent ORM pagination
  • resources/lang/en/passwords.php – contains the English language translations used for passwords messages
  • resources/lang/en/validation.php – contains the English language translations that are used for validation

Let’s open the file passwords.php

You will get the following content

<?php

return [
    'password' => 'Passwords must be at least six characters and match the confirmation.',
    'reset' => 'Your password has been reset!',
    'sent' => 'We have e-mailed your password reset link!',
    'token' => 'This password reset token is invalid.',
    'user' => "We can't find a user with that e-mail address.",
];

HERE,

  • The language file returns an associative array that has a key and value associated with it.

We will now use tinker to play around trans function that is used to retrieve and display language messages

Open the command prompt and run the following command

php artisan tinker

The above command will start tinker for you

Run the following command

trans('passwords.reset')

HERE,

  • trans('passwords.reset') calls the trans function and passes the parameter passwords.reset. passwords is the name of the language file while reset is the name of the array key in passwords.php whose value we want to display.

You will get the following message results

Laravel Tinker Trans

Let’s name look at an example that allows us to pass a parameter to the language message.

Open resources/lang/en/auth.php

You will get the following

<?php

return [
    'failed' => 'These credentials do not match our records.',
    'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];

Notice the message throttle has :seconds. :seconds is a parameter named seconds. The full colon : is used to specify a parameter.

We will now use tinker to retrieve the message throttle and pass a value.

Run the following command

trans('auth.throttle',['seconds' => 3])

HERE,

  • trans('auth.throttle'… retrieves the message throttle in the language file auth.php
  • …,['seconds' => 3]) passes the value 3 to the parameter seconds.

You will get the following results

Laravel Tinker Trans

Let’s now try the same examples using a different language

Create a new language directory /resources/lang/es for Spanish

Create a new file passwords.php in the directory /resources/lang/es

Add the following code to passwords.php

<?php

return [
    'password' => 'Las contraseñas deben coincidir y contener al menos 6 caracteres',
    'reset'    => '¡Tu contraseña ha sido restablecida!',
    'sent'     => '¡Te hemos enviado por correo el enlace para restablecer tu contraseña!',
    'token'    => 'El token de recuperación de contraseña es inválido.',
    'user'     => 'No podemos encontrar ningún usuario con ese correo electrónico.',
];

HERE,

  • The above language file returns an associative array with the same keys as the language file for English but the values returned are in Spanish and not English.

Run the following tinker command to get the current app locale

App::getLocale();

You will get the following results

"en"

Let’s now create a locale variable with the value of es

$locale = 'es'

Run the following command to change the locale from en to es

App::setLocale($locale)

Let’s confirm that the App locale has been updated

App::getLocale();

You will get the following results

"es"

Let’s now retrieve the password reset message using the trans command

trans('passwords.reset')

You will get the following results

Laravel Tinker Trans

As you can see from the above results, the reset message returned is in Spanish.

Laravel localization packages

In this section, we are going to look at two packages that simplify working with localization in Laravel

These are;

  • Laravel Localization
  • Laravel Langman

Laravel Localization

The routes of our app will be as follows

http://localhost:8888/en/admin/brands

HERE,

  • For the English language. Notice the en locale just after the domain.

    http://localhost:8888/es/admin/brands

HERE,

  • For the Spanish language. Notice the es locale just after the domain.

The above routes are made possible via Laravel localization package. The GitHub official page for Laravel localization is https://github.com/mcamara/laravel-localization

in addition to providing implementation for cool routes, Laravel localization package also provides us with middleware that automatically sets the default locale for us if the route does not specify any.

Run the following composer command to install the localization package

Installation

Open the project root directory.

Open the command prompt in the root directory and run the following command

composer require "mcamara/laravel-localization": "1.1.*"

HERE,

  • The above command will install the localization package version 1.1.*

Configuration

Now that we have installed the package, let’s configure it so that it can be used in the application

Open /config/app.php

Add the following line to the service providers array

Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,

Add the following line to the aliases

'LaravelLocalization'   => Mcamara\LaravelLocalization\Facades\LaravelLocalization::class,

Save the changes

Run the following artisan command to publish the localization configuration file

php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"

the above command will create a file in /confignamed laravellocalization.php

By default, the configuration file has English and Spanish enabled. You can enable more languages by un-commenting them.

Laravel localization middleware

We want our app to be able to set the default if locale if the user does not specify any route when accessing a resource.

Open /app/Http/Kernel.php

Add the following line to $routeMiddleware array

'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,

Save the changes

Laravel localized routes

Let’s now modify our /routes/web.php to prefix them with the locale

Route::group(['prefix' => LaravelLocalization::setLocale(),'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]], function()
{
    Route::group(['prefix' => 'admin','middleware' => 'auth','namespace' => 'Admin'],function(){
        Route::resource('customers', 'CustomersController');
        Route::resource('brands', 'BrandsController');
        Route::resource('product-categories', 'ProductCategoriesController');
        Route::resource('products', 'ProductsController');
        Route::resource('users', 'UsersController');

        Route::get('orders',[
            'uses' => 'OrdersController@index',
            'as' => 'orders.index',
            ]);
    });

    // Authentication Routes...
    $this->get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('admin/login', 'Auth\LoginController@login');
    $this->post('admin/logout', 'Auth\LoginController@logout')->name('logout');

    // Password Reset Routes...
    $this->get('admin/password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.reset');
    $this->post('admin/password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
    $this->get('admin/password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset.token');
    $this->post('admin/password/reset', 'Auth\ResetPasswordController@reset');
});

HERE,

  • Route::group(['prefix' => LaravelLocalization::setLocale(),'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]], function() prefixes the routes with the locale just after the domain name. The route group also applies the localeSessionRedirect and localizationRedirect middleware.

All the routes with the LaravelLocalization group will be localized and if the default route is not set, then the app will default to en.

Laravel Langman

Localizing a medium to large sized projects can become very complex when one has to deal with more than one language. One must ensure that all the necessary language files have been created and the required keys are present in all the files.

At times one may need to rename keys and doing this manually may take forever and it is possible to miss some keys.

This is where Laravel Langman comes in handy. It allows you to manage you language files via the command line. You can use it to

  • Rename keys
  • Find missing keys
  • Synchronizing language files
  • …and many more

Installation

We will user composer to install the package.

Run the following command

composer require themsaid/laravel-langman

let’s now add the service provider to /config/app.php

Themsaid\Langman\LangmanServiceProvider::class,

Save the changes

Run the following command to publish the configuration file

php artisan vendor:publish --provider="Themsaid\Langman\LangmanServiceProvider"

the above command will publish the config file in config/langman.php

the configuration file contains the path to the language file. The default is /resources/lang

Langman basic commands

Let’s now look at some of the commands that Langman makes available via artisan.

php artisan langman:show users

Displays all the language keys and values of the language file users.

You will get the following results

Langman Basic Commands

For experimentation purposes, remove the create_user key from /resources/lang/users.php

Run the following command

php artisan langman:show users

you will get the following results

Langman Missing Keys

As you can see from the above results, Langman has detected that the English language file is missing the key create_user

Run the following command to synchronize the files

php artisan langman:sync

Langman Sync

As you can see from the above results, the missing key create_user in the english language file has automatically been added for us.

If you run the langman:show command, you will still see the missing attribute. This is because the key was added with an empty value.

Open the file /resources/lang/users.php and add the missing value

You can read the official GitHub page for Langman for more commands https://github.com/themsaid/laravel-langman

I you would like a web based language file manager, then you can have a look at the package https://github.com/barryvdh/laravel-translation-manager

Localization Larashop Admin Panel

For the sake of simplicity, we will not display the tutorial project code in the tutorial. You can either download the attached project file or clone the branch

08_localization from the official Laradmin GitHub repository

Run the following command to clone the repository

git clone -b 08_localization https://github.com/KodeBlog/Laradmin.git laradmin

Run the following command to browser to the root of the project

cd laradmin

We will now use composer to install dependencies.

composer install

When the installation is completed, run the following artisan command

php artisan serve

The /resources/lang directory contains the language files for English and Spanish. If you speak languages other than English and Spanish, then you can help us create as many language files as possible for the tutorial project. if you find mistakes in existing files, feel free to submit corrections

Complete Tutorial Code

The complete code for this tutorial can be cloned from the following branch

git clone -b 08_localization https://github.com/KodeBlog/Laradmin.git laradmin

Run the following command to browser to the root of the project

cd laradmin

We will now use composer to install dependencies.

composer install

When the installation is completed, run the following artisan command

php artisan serve

Summary

Laravel Localization makes it possible for an app to adapt to the language and cultural requirements of a user. Laravel provides localization out of the box. Third party packages such as Laravel localization and Langman make it ridiculous easy to implement localization.

What’s next?

The next tutorial will be Laravel 5 Eloquent Relationships. We will create the database for our admin panel using migrations and define the table relationship.

Kode Blog Tutorials is dedicated to bring you update to date, high quality free tutorials. You can support us by using the social media buttons to like and share the tutorial and subscribing to our newsletter. Please use the comments section below to give us feedback.

Each week, a new Laravel tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.


...