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

2 Answers 11

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::get('localization_file_name.variable_name');

If you want to realize the possibility of language selection, you only need a few simple steps to apply:

  1. In config/app.php add this code:

    'locale' => 'ru',
    'locales' => ['ru', 'en'],
    

    The name of the locale can be any.

  2. In app/Http/Middleware create a new file named Locale.php. The contents of the file should be something like this:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use App;
    use Config;
    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');
         if (in_array($raw_locale, Config::get('app.locales'))) {
           $locale = $raw_locale;
         }
         else $locale = Config::get('app.locale');
           App::setLocale($locale);
           return $next($request);
       }
     }
    
  3. In app/Http/Kernel.php in $middlewareGroupsarray add the this line:

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

  4. In routes/web.php add:

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

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.