0

问题

Session::get不在基本控制器中工作

以下情况未显示正确的会话值

登录控制器

class LoginController extends \App\Http\Controllers\Web\BaseController
{
    public function Login() {
        return View("UserManagement.Auth.Login.login");
    }
}

基本控制器

class BaseController extends Controller
{
    public function __construct() {
        if(\Session::get("CurrentLanguage") != null) {
            dd('here');
            \App::setLocale(\Session::get("CurrentLanguage"));
        }
        else {
            dd('here1');
            \Session::put("CurrentLanguage", "en");
            \App::setLocale("en");
        }
    }
}

下面的案例显示正确的会话值

基本控制器

class BaseController extends Controller
{

}

登录控制器

class LoginController extends \App\Http\Controllers\Web\BaseController
{
    public function Login() {
        if(\Session::get("CurrentLanguage") != null) {
            dd('here');
            \App::setLocale(\Session::get("CurrentLanguage"));
        }
        else {
            dd('here1');
            \Session::put("CurrentLanguage", "en");
            \App::setLocale("en");
        }
        return View("UserManagement.Auth.Login.login");
    }
}

这里的问题是,我必须在许多控制器中使用基本控制器。有什么方法可以使会话在基本控制器中工作?

4

1 回答 1

0

根据以下 URL,您不再能够在 Laravel 5.3 的控制器的构造函数中使用会话。这是因为在构造控制器的时间点,处理会话的中间件尚未运行。显然,能够访问控制器中的会话从来都不是预期的功能。由于这会影响会话,因此您也无法在控制器的构造函数中访问经过身份验证的用户。

然而,解决这个问题的一种方法是在构造函数中使用基于闭包的中间件。

class BaseController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if(\Session::get("CurrentLanguage") != null) {
                dd('here');
                \App::setLocale(\Session::get("CurrentLanguage"));
            }
            else {
                dd('here1');
                \Session::put("CurrentLanguage", "en");
                \App::setLocale("en");
            }

            return $next($request);
        });
    }
}

这是可行的,因为您的控制器只是定义了一个中间件,以便在会话可用之后运行。

它在您的第二个示例中起作用的原因是您正在以控制器方法访问会话。在那个时间点会话可用,因为中间件已经运行。

于 2017-02-08T09:15:52.603 回答