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

    Route::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:

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

    Define The Controller

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

    php artisan make:controller LanguageController
    
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Session;
    
    class LanguageController extends Controller
    {
        public function __invoke($lang)
        {
            // 
        }
    }
    
    

    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:

        public function __invoke($lang)
        {
            $availableLanguage = ['ar', 'en', 'fr'];
    
            if (in_array($lang, $availableLanguage)) {
    
                $locale = Session::put('lang', $lang);
    
                App::setLocale($locale);
    
                return back();
            }
        }
    

    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:

    php artisan make:middleware LanguageSwitcher
    

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

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    
    class LanguageSwitcher
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle(Request $request, Closure $next)
        {
    
            if (session()->has('lang')) {
                app()->setLocale(session()->get('lang'));
            }
    
            if (!session()->has('lang')) {
                app()->setLocale(config('app.locale'));
            }
    
            return $next($request);
        }
    }
    

    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

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

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

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

    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

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

    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:

    {
        "Home": "Accueil"
    }
    

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

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

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

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

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

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

    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

    @lang('en.auth.failed')
    

    In normal PHP file, use lang helper

    lang('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

    I'm a full stack web developer and telecommunications engineer who love to share knowledge and build stuff online!


    Comments

    Join Our Newsletter

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

    Our news letter sent once a week, every tuesday.