会话变量BaseController中的问题

Problem

Session::get not working in Base Controller

Below case does not shows correct session value

Login Controller

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

Base Controller

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");
        }
    }
}

Below case shows correct session value

Base Controller

class BaseController extends Controller
{

}

Login 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");
    }
}

Here the problem is, I have to use Base Controller in many controllers. Is there any way to make the session work in Base Controller?

According to the following URL, you are no longer able to use the session in the constructor of a controller in Laravel 5.3. This is because at the point in time that your controller is constructed the middleware that deals with the session has not yet run. Apparently, it was never an intended feature to be able to access the session in the controller. Since this affected sessions, you will not be able to access the authenticated user in the controller's constructor either.

A way around this however is to use a closure based middleware in your constructor.

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);
        });
    }
}

This works because your controller is simply defining a middleware to run at a later time after which the session is available.

The reason it works in your second example is that you're accessing the session in a controller method. At that point in time the session is available because the middleware will have run.