Laravel trans helper function not picking the right file

4.6k views Asked by At

I'm building a website in Laravel, I'm having it get the browser language and set the website's language accordingly.

Problem is, nothing in Registrar.php seems to get translated in English or Dutch

Could anyone please help me out? Thanks, g3

1

There are 1 answers

1
Emeka Mbah On BEST ANSWER

To make this work you need to use a middleware to set Locales:

Create a LocaleMiddleware.php inside app/http/middleware directory

//LocaleMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Store as Session;
use Illuminate\Contracts\Auth\Guard as Auth;


class LocaleMiddleware {

    public function __construct(Session $session)
    {
        $this->session      = $session;
    }


  //Languages available in your resources/lang

   protected $languages = ['en','es', 'nl-be'];



   public function handle($request, Closure $next)
   {
       $langlist = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

       // We just want the main language
        $lang = substr($langlist,0,2);

        if(isset($this->languages[$lang])){
           app()->setLocale($lang);
        }else{
           //You may log this here
        }

        return $next($request);
     }

 }

Then register the middleware in app\httpe.kernel.php in $middleware array

/**
 * The application's global HTTP middleware stack.
 *
 * @var array
 */
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

     .........

    \App\Http\Middleware\LocaleMiddleware::class,
];

Creating lang files

You need to create separate folders for all languages you want to support and translate the files in them accordingly e.g nl-be\validation.php.

You can start by coping the contents of resources/lang/en to resources/lang/nl-be, then translate the contents ofnl-be\validation.php` to dutch equivalent

enter image description here