DEV Community

Imran Hossain (Rubab)
Imran Hossain (Rubab)

Posted on • Updated on

Create a Multi Language Based Website With Laravel

This article goes in detailed on how to make a website multilingual in Laravel. Users will be able to set the language English or Bangla and the whole site will be translated accordingly.

First, create a Middleware called SetLocale. To create the middleware, open your terminal and run below command:

php artisan make:middleware SetLocale
Enter fullscreen mode Exit fullscreen mode

It will create SetLocale.php file inside Middleware Folder. We will use session to store user’s selected language. Now in the handle funtion add below code so that the middleware can check the session data to set the website language when a web route uses the middleware.

app/Http/Middleware/SetLocale.php

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        if(is_null(session('locale')))
            session(['locale'=> 'en']); // set language english if language is not set in session

        app()->setLocale(session('locale')); // set the session's language to our application

        return $next($request); // this will already be available in the handle request. It just passes the request to next handle.
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, we need to register our middleware in the Kernel.

app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\SetLocale::class
    ]
];

protected $routeMiddleware = [
    'setLocale' => \App\Http\Middleware\SetLocale::class
];
Enter fullscreen mode Exit fullscreen mode

We will apply our middlware inside our web routes. Also we will create a change language route where selected route will be set to the session.

routes/web.php
--------------
// middlware applied on base route
Route::group(['middleware' => ['setLocale']], function () {
    Route::get('/', function () {
        return view('welcome');
    });
});

// language change option route
Route::get('/change-language/{lang}', function($lang){
    if(in_array($lang,['en','bn'])){
        session(['locale'=> $lang]);
    }
    return back(); // return to the previous page from where language changed by user
})->name('change-language');
Enter fullscreen mode Exit fullscreen mode

Now it’s time to creat language files where we will keep our translations. There are two ways to translate language.One is using translated language in php file or using json file.

We can use php file for specific purpose. let’s say we need translation only for blog related string for blog feature. This also allow us multi level nested keys for translation mapping.

// for english translation
resources/lang/en/blog.php
return [
    'title' => 'Title',
    'category' => 'Category'
];

// for bangla translation
resources/lang/bn/blog.php
return [
    'title' => 'Title',
    'category' => 'Category'
];
Enter fullscreen mode Exit fullscreen mode

On the other hand, we can use a json file to list all our language strings for direct string mapping.

//for bangla translation of strings.
resources/lang/bn.json
{
    "Welcome to Code With Rubab": "কোড উইথ রুবাব এ আপনাকে স্বাগতম"
}
Enter fullscreen mode Exit fullscreen mode

Finally, we will will add language change select option in our welcome blade file. Also translated language will be seen a user changes a language.

resources/views/welcome.blade.php

<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
    {{ session('locale') === 'bn' ? 'বাংলা' : 'English' }}
</button>
<ul class="dropdown-menu">
    <li><a class="dropdown-item" href="{{ route('change-language','en') }}">
            English
        </a>
    </li>
    <li><a class="dropdown-item" href="{{ route('change-language','bn') }}">
            বাংলা
        </a>
    </li>
</ul>

// translate string based on the selected language
<div>
    {{ __('Welcome to Code With Rubab') }}

    // translate from blog language file
    @lang('blog.title') 
    trans('blog.category')
</div>
Enter fullscreen mode Exit fullscreen mode

Bonus:

Add auto language set based on Country.

Install the package geoip

composer require torann/geoip
Enter fullscreen mode Exit fullscreen mode

Change the CACHE_DRIVER=array in env file.

modify the SetLocale middleware for automatically setting language in the handle function.

if(is_null(session('locale'))){
    $lang = geoip()->getLocation()->country === 'Bangladesh' ? "bn"  : "en";
    session(['locale'=> $lang]);
}
app()->setLocale(session('locale'));

return $next($request);
Enter fullscreen mode Exit fullscreen mode

This is the part one for static based translation. In the next part, we will use dynmaic based translation where a blog post will be uploaded in multi language and users will be able to read blog post in different languages.


Thank you for reading my article. You can join code with rubab for web development-related queries & discussions.

Also, you can find me on:

Linkedin For Regular Posts

My website

My Facebook Page

My Youtube Channel

Top comments (0)