DEV Community

faisal ahmed
faisal ahmed

Posted on • Originally published at Medium

Auto translate page based on subdomain in a Laravel application

Scenario:
I have a web application which is mainly built in english but the client required a functionality where the the website could be loaded in multiple subdomains based on country. For example; the main website is at www.domain.com which will show content in english but if the website is accessed in bd.domain.com then the same english content needed to be translated seamlessly using google translate.

Solution:
I have already created a writeup where I toggled laravel locale based on subdomain by identifying the subdomain in AppServiceProvider. As an extension to that work I also introduced two variables that got passed to all available views using view::share() method. The resulting code looks something like this -

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        if(!empty($_SERVER['HTTP_HOST'])){
            //subdomain specific locale
            $subdomain = current(explode('.', $_SERVER['HTTP_HOST']));

            if (in_array($subdomain, ["www","in"])) {
                if($subdomain !== 'www'){
                    app()->setLocale($subdomain);
                    config('app.url',$subdomain.'.domain.com');
                    View::share('translate',true);
                    if($subdomain == 'in') View::share('translate_lang','hi');
                    if($subdomain == 'bd') View::share('translate_lang','bn');                    
                } else {
                    app()->setLocale('en');
                    config('app.url','www.domain.com');
                    View::share('translate',false);
                    View::share('translate_lang','en');
                }            
            } else {
                app()->setLocale('en');
                config('app.url','www.domain.com');
            }
        }
    }
} 
Enter fullscreen mode Exit fullscreen mode

This meant now I had two variable available which I could check in the blade templates to load the google translate JavaScript code block and initialize the translation on page load. The blade layout file looked as follows -

   <html>
    <head>
    </head>
    <body>
      @if($data['translate'] == true)<div id="google_translate_element" style="display:none;"></div>@endif
      <div class="container">
        <p>Your content goes here.</p>
      </div>
      @if(view()->shared('translate') == true)
      <script type="text/javascript">
      function setCookie(key, value, expiry) {
          var expires = new Date();
          expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
          document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
      }

      function googleTranslateElementInit() {
          setCookie('googtrans', '/en/{{view()->shared("translate_lang")}}',1);
          new google.translate.TranslateElement({
              pageLanguage: 'en'
          }, 'google_translate_element');
      }
      </script>
      <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">
      </script>
      @endif
    </body>
  </html>
Enter fullscreen mode Exit fullscreen mode

So, now when the website is accessed via www.domain.com it loads the regular english language content but if the same page is visited via bd.domain.com then the same english content is translated to bengali language on page load. Further more; if there are certain content that needs to be loaded using local language file that also works as laravel sets the local to appropriate language based on subdomain.

Top comments (0)