Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Laravel's App::getLocale() method inconsistent?

Tags:

php

laravel

I'm using 2 languages in my Laravel 5.2 app. There is a simple password-reminder page I'm implementing currently, and for reasons unknown to me I have problems in sending the new-password email in the correct language.

Let's say I see the page in German. In the view of the page, I echo 2 values, using Facades:

echo App::getLocale();
echo Session::get('locale');

The page is served in German, so both values echo de.

Now, I enter an email address into the form and submit it. The input gets to a controller method and calls a library to send a new password to the user:

public function resetPassword() {
    // Validate the input, retrieve the user...    

    Mailer::sendNewPasswordEmail($user); // Call to the library sending emails
}

Finally, in the library, I var_dump the same 2 values, like this:

public static function sendNewPasswordEmail($user) {
    var_dump(App::getLocale());
    var_dump(Session::get('locale'));
    die;
}

In this case, Session::get('locale') still equals de, but App::getLocale() shows en.

Why, why, why?

In my email template, I'm using the Blade's @lang() directive. As far as I know, the directive checks the application locale to determine which translation to serve. In my case, the email is being sent always in English and I have no clue why App::getLocale() returns a different value in the view and during the next POST request I'm making.

This is not the first time this happens, btw. At times is seems that views "know" more about the actual application locale, than the controllers, models or libraries. Confusing.

Ideas?

like image 277
lesssugar Avatar asked Jul 06 '16 16:07

lesssugar


1 Answers

Laravel 5.2 App_Locale is not persistent. the only way I've found to make locales work properlly is creating a middleware that calls App::setLocale() like this:

<?php namespace App\Http\Middleware;

use Closure;
use Session;
use App;
use Config;

class Locale {

   /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        App::setLocale(Session::get('locale'));
        return $next($request);
    }

}

Register your middleware on Kernel.php

protected $middleware = [
    .
    .
    .

   'App\Http\Middleware\Locale'
];
like image 179
Franklin Rivero Avatar answered Nov 07 '22 00:11

Franklin Rivero