简体   繁体   English

讲解Laravel 5.3 构造函数中Session的使用方法

[英]Explain how to use Session In The Constructor Laravel 5.3

according to laravel docs https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors i can no longer access the session in the construct because the middleware isnt loaded yet , they provided an example that i couldnt understand根据laravel docs https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors我无法再访问构造中的会话,因为中间件尚未加载,他们提供了一个我无法理解的示例

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->projects = Auth::user()->projects;

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

how do i access my session here inside that function?我如何在该函数中访问我的会话? , an explaination would do ,一个解释会做

将它放在将处理请求的控制器的__construct()函数中。

The Laravel docs state that you can't access middleware anymore in the constructor, because it hasn't been loaded yet. Laravel 文档声明您不能再在构造函数中访问中间件,因为它尚未加载。

By using that specific Closure, you're actually forcing php (and Laravel) to load whatever logic you have in the Closure as middleware.通过使用特定的 Closure,您实际上是在强制 php(和 Laravel)加载您在 Closure 中拥有的任何逻辑作为中间件。 Take a look at the basic controller class provided by Laravel and see if you can connect the dots.看看 Laravel 提供的基本控制器类,看看能不能把点连起来。

Essentially, you're hacking the framework.从本质上讲,您正在破解框架。

That being said, it's really bad practice and you shouldn't temper with your session in controller's constructors.话虽如此,这确实是不好的做法,您不应该在控制器的构造函数中调整会话。

 public function __constrcut(){
    //changing language accordding to session
    $this->middleware(function($request,$next){
        app::setLocale(Session::get('locale'));
        return $next($request);
    });

This code used for changing language according to session the version which i use laravel 5.5 Note: you must call the middelware first then use session as the constructor not see session this works for me此代码用于根据会话更改语言我使用的版本 laravel 5.5 注意:您必须先调用中间件然后使用会话作为构造函数看不到会话这对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM