How can I find the current language in a Laravel view?
Asked Answered
C

11

22

I'm using the Laravel Lang class for localization of my web app. I've added two languages to the languages array in application/config/application.php. This changes the default language it uses for localization to whatever the first part of the URI indicates (e.g. bla.com/en/bla and bla.com/co/bla). Now I need to be able to check what the current default language is in my view. However, the Lang class provides no way of checking this as far as I've been able to figure out, as the Lang::$language variable is protected. Is there any way of checking this apart from manually parsing the URI?

Ciera answered 3/10, 2012 at 10:20 Comment(0)
A
8

BenjaminRH's answer is very good, and his suggested approach works perfectly. I've improved the snippet a bit. Now it detects the browser language and checks if that language is supported according to the application's config file.

It's a quick hack, but it works on my app. Note that the application language is also set now. Feel free to use ore improve it.

Route::filter('before', function()
{
    // current uri language ($lang_uri)
    $lang_uri = URI::segment(1);

    // Set default session language if none is set
    if(!Session::has('language'))
    {
        // use lang in uri, if provided
        if(in_array($lang_uri, Config::get('application.languages')))
        {
            $lang = $lang_uri;  
        }
        // detect browser language
        elseif(isset(Request::server('http_accept_language')))
        {
            $headerlang = substr(Request::server('http_accept_language'), 0, 2);

            if(in_array($headerlang, Config::get('application.languages')))
            {
                // browser lang is supported, use it
                $lang = $headerlang;
            }
            // use default application lang
            else
            {
                $lang = Config::get('application.language');
            }
        }
        // no lang in uri nor in browser. use default
        else 
        {
                // use default application lang
                $lang = Config::get('application.language');            
        }

        // set application language for that user
        Session::put('language', $lang);
        Config::set('application.language',  $lang);
    }
    // session is available
    else
    {
        // set application to session lang
        Config::set('application.language', Session::get('language'));
    }

    // prefix is missing? add it
    if(!in_array($lang_uri, Config::get('application.languages'))) 
    {
        return Redirect::to(URI::current());
    }
    // a valid prefix is there, but not the correct lang? change app lang
    elseif(in_array($lang_uri, Config::get('application.languages')) AND $lang_uri != Config::get('application.language'))
    {
        Session::put('language', $lang_uri);
        Config::set('application.language',  $lang_uri);    
    }
});
Accentuate answered 21/11, 2012 at 14:28 Comment(6)
Nice, though to keep the syntax Laravely (making up words here) use Request::server('http_accept_language') instead of directly accessing $_SERVER.Minni
I trust you on this, changed the snippet :)Accentuate
I like what you did with it. Accepted.Ciera
I've got an Unhandled Exception error using your snippet (Can't use function return value in write context for the line elseif(isset(Request::server('http_accept_language')))) with PHP 5.3.5 and Laravel 3.2.14, I've edited your answerSolubility
My edit was rejected by people who only want to collect reputation for this reason : "This edit changes too much in the original post; the original meaning or intent of the post would be lost.". Many thanks.Solubility
As Epoc pointed out, the code above doesn't work. You should use array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER) to check if the browser language was send.Psychodiagnosis
S
37

The cleanest way to know the current language of your website in Laravel appears to be :

Lang::locale();

https://laravel.com/api/5.8/Illuminate/Translation/Translator.html#method_locale

It's different than this command that will return the default language of your website :

Config::get('app.locale');
Seraphic answered 8/7, 2015 at 16:40 Comment(0)
C
23

An alternative, a bit shorter way could be using something like this:

app()->getLocale()

The advantage of this is that IDEs such as PHPStorm recognize this function and can help you develop much faster.

Chaffer answered 26/1, 2017 at 11:4 Comment(0)
A
8

BenjaminRH's answer is very good, and his suggested approach works perfectly. I've improved the snippet a bit. Now it detects the browser language and checks if that language is supported according to the application's config file.

It's a quick hack, but it works on my app. Note that the application language is also set now. Feel free to use ore improve it.

Route::filter('before', function()
{
    // current uri language ($lang_uri)
    $lang_uri = URI::segment(1);

    // Set default session language if none is set
    if(!Session::has('language'))
    {
        // use lang in uri, if provided
        if(in_array($lang_uri, Config::get('application.languages')))
        {
            $lang = $lang_uri;  
        }
        // detect browser language
        elseif(isset(Request::server('http_accept_language')))
        {
            $headerlang = substr(Request::server('http_accept_language'), 0, 2);

            if(in_array($headerlang, Config::get('application.languages')))
            {
                // browser lang is supported, use it
                $lang = $headerlang;
            }
            // use default application lang
            else
            {
                $lang = Config::get('application.language');
            }
        }
        // no lang in uri nor in browser. use default
        else 
        {
                // use default application lang
                $lang = Config::get('application.language');            
        }

        // set application language for that user
        Session::put('language', $lang);
        Config::set('application.language',  $lang);
    }
    // session is available
    else
    {
        // set application to session lang
        Config::set('application.language', Session::get('language'));
    }

    // prefix is missing? add it
    if(!in_array($lang_uri, Config::get('application.languages'))) 
    {
        return Redirect::to(URI::current());
    }
    // a valid prefix is there, but not the correct lang? change app lang
    elseif(in_array($lang_uri, Config::get('application.languages')) AND $lang_uri != Config::get('application.language'))
    {
        Session::put('language', $lang_uri);
        Config::set('application.language',  $lang_uri);    
    }
});
Accentuate answered 21/11, 2012 at 14:28 Comment(6)
Nice, though to keep the syntax Laravely (making up words here) use Request::server('http_accept_language') instead of directly accessing $_SERVER.Minni
I trust you on this, changed the snippet :)Accentuate
I like what you did with it. Accepted.Ciera
I've got an Unhandled Exception error using your snippet (Can't use function return value in write context for the line elseif(isset(Request::server('http_accept_language')))) with PHP 5.3.5 and Laravel 3.2.14, I've edited your answerSolubility
My edit was rejected by people who only want to collect reputation for this reason : "This edit changes too much in the original post; the original meaning or intent of the post would be lost.". Many thanks.Solubility
As Epoc pointed out, the code above doesn't work. You should use array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER) to check if the browser language was send.Psychodiagnosis
C
7

In the newer Laravel versions, you can get the current language with:

Config::get('app.locale');
Chuch answered 2/9, 2014 at 18:35 Comment(0)
H
7

This would work fine

lang="{{ app()->getLocale() }}"
Heelpost answered 20/8, 2017 at 10:2 Comment(0)
C
4

I've figured out a solution to the language problem (thanks to nickstr on the IRC and the accepted answer to this question). It involves storing the current language as a session variable, which is updated when the language uri segment is changed.

Route::filter('before', function()
{
    // Do stuff before every request to your application...

    // Default language ($lang) & current uri language ($lang_uri)
    $lang = 'he';
    $lang_uri = URI::segment(1);

    // Set default session language if none is set
    if(!Session::has('language'))
    {
        Session::put('language', $lang);
    }

    // Route language path if needed
    if($lang_uri !== 'en' && $lang_uri !== 'he')
    {
        Return Redirect::to($lang.'/'.URI::current());
    }
    // Set session language to uri
    elseif($lang_uri !== Session::get('language'))
    {
        Session::put('language', $lang_uri);
    }
});
Ciera answered 3/10, 2012 at 12:2 Comment(0)
I
3

This might help. Config::get('application.language')

Impulse answered 7/2, 2013 at 4:43 Comment(0)
B
2

You can use

https://github.com/mcamara/laravel-localization

Laravel Localization uses the URL given for the request. In order to achieve this purpose, a group should be added into the routes.php file. It will filter all pages that must be localized.

    // app/routes.php

    Route::group(array('prefix' => LaravelLocalization::setLanguage()), function()
    {
        /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
        Route::get('/', function()
        {
            return View::make('hello');
        });

        Route::get('test',function(){
            return View::make('test');
        });
    });

    /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

Once this group is added to the routes file, an user can access to all languages added into the 'languagesAllowed' ('en' and 'es' for default, look at the config section to change that option). For example, an user can now access to two different languages, using the following addresses:

http://laravel.com/en

http://laravel.com/es

http://laravel.com

Brandonbrandt answered 4/10, 2013 at 10:3 Comment(0)
H
2

I use App::getLocale() which is probably the most supported way as the App::setLocale('EN') method is used in the documentation.

You can use this method everywhere. If it throughs an error somewhere, you can use \App::... to make it work.

I'm using Laravel 5.0.

Honeydew answered 22/11, 2016 at 10:43 Comment(0)
P
2

Your can get current language in laravel blade by:

{{Lang::locale()}}

Pyrrha answered 18/6, 2020 at 5:16 Comment(1)
Better than other solutions.Instrumental
M
0

The Lang class is specifically for outputting the correct language and as you say manages the language internally.

Looking through the API there is no method to help you directly with this and parsing the URI to get the language would seem the appropriate course of action.

You can always just do this to retrieve the language string in the URI:

$language = URI::segment(1);

Examining Laravel Requests

Minni answered 3/10, 2012 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.