Search code examples
laravelmultilingualsetlocale

Laravel frontend and backend with different multilanguage


In Laravel at the same time i need have different language/locale in site frontend and backend(administration). Frontend need 4 languages(en,de,fr,it), backend need 3 languages(en,lt,es).
Example: In browser i have two open tabs - 1 tab frontend (lang: de), 2 tab backend (lang: en). How to do it ? with setLocale? or i need different array for example backend?


Solution

  • One way you can easily handle this is by creating two BaseController classes for your frontend and backend controllers.

    You can then set different languages for your frontend and backend from the right BaseController constructor using App::setLocale method.

    Example:

    <?php
    
    class FrontendBaseController extends Controller
    {
        public function __construct()
        {
            App::setLocale(Session::get('frontend-locale'));
        }
    }
    
    
    class BackendBaseController extends Controller
    {
        public function __construct()
        {
            App::setLocale(Session::get('backend-locale'));
        }
    }
    
    class HomeController extends FrontendBaseController
    {
        public function __construct()
        {
    
        }
    }
    
    class BackendDashboardController extends BackendBaseController
    {
        public function __construct()
        {
    
        }
    }
    

    In the above example, I'm retrieving the current locale from the session. You can put your language files in the app/lang folder. I will suggest you to have separate folders for your frontend and backend language files.

    Example folder structure:

    /app
        /lang
            /en
                backend/
                    dashboard.php
    
                frontend/
                    home.php
    
            /de
                backend/
                    dashboard.php
    
                frontend/
                    home.php
    

    Sample content of app/lang/en/backend/dashboard.php:

    <?php
    return array(
        'welcome' => 'Welcome to Backend!'
    );
    

    You can output the value of welcome key for example with echo Lang::get('backend/dashboard.welcome');.

    I hope you got the idea. For more details, feel free to check out the official documentation.