⌘K
Noting Found

View all related articles

Easy Steps To Make Multiple languages Application Using Laravel

Laravel 3 mins read

Table of Content

    Introduction

    Nowadays, multiple languages in some websites will be a mandatory thing because of different nationalities visits your website. So, Today We'll bring an easy way on how to deal with multiple languages in Laravel application and HEY! No packages needed!.

    Prerequisite

    You need to have basic knowledge on how Laravel routes, controllers and middleware works.

    Create New Route & Controller

    You need to Set up a route inside routes/web.php and a new Controller Called in app\Http\Controllers called LanguageController (In this example) Like So:

    Define The Route

    1Route::get('/lang/{lang}', LangController::class)->name('lang.switcher');

    The name method is to define the name of the route to easily call it in your application. So, you don't need to change the route path in every part of your application if you decide to change it in your route.

    Note: You can access the route by:

    1$lang = 'your-prefered-language';
    2route('lang.switcher', $lang);

    Define The Controller

    You can create a new controller by the command line using artisan command:

    1php artisan make:controller LanguageController
    1<?php
    2 
    3namespace App\Http\Controllers;
    4 
    5use Illuminate\Http\Request;
    6use Illuminate\Support\Facades\App;
    7use Illuminate\Support\Facades\Session;
    8 
    9class LanguageController extends Controller
    10{
    11 public function __invoke($lang)
    12 {
    13 //
    14 }
    15}

    In our case we use invoke magic method, and it's PHP built-in function, and with it, you don't need to define a method name inside your route.

    Write The Logic and Protecting Your Route

    You need to notice that the method accept any value when someone call /lang/{lang} because {lang} it's a parameter, and we should limit the needs of the values in it.

    In your LanguageController put the following code:

    1public function __invoke($lang)
    2{
    3 $availableLanguage = ['ar', 'en', 'fr'];
    4 
    5 if (in_array($lang, $availableLanguage)) {
    6 
    7 $locale = Session::put('lang', $lang);
    8 
    9 App::setLocale($locale);
    10 
    11 return back();
    12 }
    13}

    The $availableLanguage is your available language in the application and in_array function is a PHP built-in to determine if the input (which in our case $lang) has the following values or not (which in our case the array of values $availableLanguage).

    If the $lang match on or our $availableLanguage. So, You are good to go to the next step, which is storing a session with the given input and Set the Application Locale to the given language.

    Finally, We're returning and let the user complete where he/she stopped.

    Define The Middleware

    We are close to finish our mission! The final step (before the tiny final step) to create a middleware by:

    1php artisan make:middleware LanguageSwitcher

    In The LangSwitcher Middleware and in the handle method, do this:

    1<?php
    2 
    3namespace App\Http\Middleware;
    4 
    5use Closure;
    6use Illuminate\Http\Request;
    7 
    8class LanguageSwitcher
    9{
    10 /**
    11 * Handle an incoming request.
    12 *
    13 * @param \Illuminate\Http\Request $request
    14 * @param \Closure $next
    15 * @return mixed
    16 */
    17 public function handle(Request $request, Closure $next)
    18 {
    19 
    20 if (session()->has('lang')) {
    21 app()->setLocale(session()->get('lang'));
    22 }
    23 
    24 if (!session()->has('lang')) {
    25 app()->setLocale(config('app.locale'));
    26 }
    27 
    28 return $next($request);
    29 }
    30}

    And this middleware basically telling you if your application session has lang key, get the key and set the local upon on it, and if you don't set the local to the default in config/app.php under the key locale. Furthermore, return the next request.

    Register The Middleware

    Option One

    There are two type of registering, if you want to set you language feature only on a part of your application, go to app/Http/Kernel.php and add the following in routeMiddleware

    1protected $routeMiddleware = [
    2 // ...
    3 'lang' => \App\Http\Middleware\LanguageSwitcher::class,
    4];

    Inside you web.php routes, add the middleware name in your targeted routes

    1Route::group([
    2 'middleware' => 'lang',
    3], function () {
    4 // add your routes here
    5});

    Option Two

    If you want to set the multiple language feature in your entire application, then you could add your middleware into $middleware protected property

    1protected $middleware = [
    2 // ...
    3 \App\Http\Middleware\LanguageSwitcher::class,
    4]

    Add Language Files

    There are two types of language file, and you can work with any method you prefer.

    You Language file lives in resources/lang folder.

    Option 01

    You can add the {$langKey}.json inside resources/lang folder and set the key as the original word and the value as the translated word, like so:

    1{
    2 "Home": "Accueil"
    3}

    Each word you want to translate, add it between the escape helper

    1<p>
    2 All Set You can go {{ __('Home') }} Now!
    3</p>

    Even You can pass parameters to the translated words (in case you have dynamic data such as numbers)

    1<p>
    2 {{ __('Your Visitors This Month is :visitor_count', [
    3 'visitor_count' => 100K
    4 ]) }}
    5</p>

    If you want to translate the last phrase, you can do the following:

    1{
    2 "Your Visitors This Month is :visitor_count": "Vos visiteurs ce mois-ci sont :visitor_count"
    3}

    Option 02

    You can use the array way. In resources/lang you will notice that there's a folder called en and this folder references the English language. So, if you want to add new Lang, all what you need to do is to create folder with the language key such as fr and add files in it as arrays.

    You can call thus files like the following:

    In blade use, the directive @lang

    1@lang('en.auth.failed')

    In normal PHP file, use lang helper

    1lang('en.auth.failed')

    Note:

    You can pass parameter like the json way and nothing changes between the two methods. Exactly the same approach.

    Something You Will Need While Working With Multi-Lang

    When you are working on a new language, you will face some default error messages and validation built-in Laravel itself. So, refer to this repository and pick whatever language you want. It has more than 77 language updated every month.

    Conclusion

    today We learned about how to set up multiple languages in Laravel application with easy and straightforward steps.

    Hope this help someone around and if you have any questions let me know in the comment section, I'll be more than happy to answer them.

    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer | Technical Writer

    Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

    Comments

    Join our newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    We care about the protection of your data. Read our Privacy Policy.