Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch current locale in view in Laravel 5.3

I am making a bilingual app. I am using same routes for each but I am using different views for both languages. Whenever I want to redirect to a route I want to pass {{ route('test.route', 'en') }}. Where I am passing en, I want to fetch the current locale value from the view and then pass it to the route. Please help.

like image 279
Fahad Khan Avatar asked Jan 06 '17 12:01

Fahad Khan


People also ask

What is locale in laravel?

Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the lang directory.

What is @lang in laravel?

Laravel-lang is a collection of over 68 language translations for Laravel by developer Fred Delrieu (caouecs), including authentication, pagination, passwords, and validation rules. This package also includes JSON files for many languages.

How does laravel know language?

First you set $availableLangs the array of the available languages in your app, you may use config\app. php instead of initializing the array in the middleware as I did. If the first language is available in the request language data, it sets the locale, if not, it will search the next one, and so on.


2 Answers

try this. It will give the locale set in your application

Config::get('app.locale')

Edit:

To use this in blade, use like the following, to echo your current locale in blade.

{{ Config::get('app.locale') }}

If you want to do a if condition in blade around it, it will become,

   @if ( Config::get('app.locale') == 'en')

   {{ 'Current Language is English' }}

   @elseif ( Config::get('app.locale') == 'ru' )

   {{ 'Current Language is Russian' }}

   @endif

To get current locale,

app()->getLocale()
like image 72
Arun Code Avatar answered Nov 09 '22 09:11

Arun Code


At first create a locale route and controller :

Route::get('/locale/{lang}', 'LocaleController@setLocale')->name('locale');

class LocaleController extends Controller
{
    public function setLocale($locale)
    {
        if (array_key_exists($locale, Config::get('languages'))) 
        {
            Session::put('app_locale', $locale);
        }
        return redirect()->back();
    }
}

Now you can check easily in every page:

  $locale = app()->getLocale();
  $version = $locale == 'en' ? $locale . 'English' : 'Bangla';
like image 45
rashedcs Avatar answered Nov 09 '22 09:11

rashedcs