user199320
user199320

Reputation: 157

Change language in Laravel 5

I just begin to use Laravel 5.4, In the login.blade.php i have

enter image description here

I don't like to put plain text in html code, is there a solution to make all the texts in seperate lang files to use them dynamically?

Thank you

Upvotes: 6

Views: 44629

Answers (3)

Alex Yapryntsev
Alex Yapryntsev

Reputation: 589

The resources/lang folder contains localization files. The file name corresponds to the view that it will be used. In order to get a value from this file, you can simply use the following code:

`Lang::geConfig; use Session;

    class Locale
    {
      /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Closure  $next
       * @return mixed
       */
       public function handle($request, Closure $next)
       {
         //$raw_locale = Session::get('locale');
         $raw_locale = $request->session()->get('locale');
         if (in_array($raw_locale, Config::get('app.locales'))) {
           $locale = $raw_locale;
         }
         else $locale = Config::get('app.locale');
           App::setLocale($locale);
           return $next($request);
       }
     }
  1. In app/Http/Kernel.php in $middlewareGroups=[ ... ] add the following line:

    \App\Http\Middleware\Locale::class,

  2. In routes/web.php add:

    Route::get('setlocale/{locale}', function ($locale) {
      if (in_array($locale, \Config::get('app.locales'))) {
        session(['locale' => $locale]);
      }
      return redirect()->back();
    });
    

Upvotes: 46

vishal dobariya
vishal dobariya

Reputation: 309

Try this!

{{ @lang('messages.login') }}

Now Add login key with it's value under language file as below

return['login'=>'Login']; // write inside messages file

and Set your APP Config Local Variable Like 'en','nl','us'

App::setLocale(language name); like 'en','nl','us'

Upvotes: 4

Mariusz
Mariusz

Reputation: 246

Laravel has a localization module.

Basically, you create a file, ex: resources/lang/en/login.php and put

return [
    'header' => 'Login'
];

And in your template you use @lang('login.header') instead of Login.

You can have as many files in your /resources/lang/en directory and using @lang blade directive you put your file name (without extension) and desired value separated with dot.

Upvotes: 0

Related Questions