lesssugar lesssugar - 2 months ago 5x
PHP Question

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

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

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) {

In this case,
still equals
, but

Why, why, why?

In my email template, I'm using the Blade's
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
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.



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)
        return $next($request);


Register your middleware on Kernel.php

protected $middleware = [