Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controller的构造函数里面使用中间件异常 #55

Open
shark2202 opened this issue Nov 10, 2020 · 1 comment
Open

Controller的构造函数里面使用中间件异常 #55

shark2202 opened this issue Nov 10, 2020 · 1 comment

Comments

@shark2202
Copy link

shark2202 commented Nov 10, 2020

BaseController.php

class BaseAgentController extends Controller
{
    /**
     * @var $user Collection
     */
    protected $user;

    public function __construct()
    {
        //执行中间件获取用户信息
        $this->middleware(function ($request, $next) {
            $this->user = collect(Auth::user())->except(['permissions', 'roles']);
            return $next($request);
        });
    }

}

IndexController.php

class IndexController extends BaseAgentController
{

    public function index(Request $request)
    {
        $user = $this->user;//这个地方有时能够获取到数据,有的时候不能获取到数据,获取到的是NULL

        return view('admin.index.index', compact('user'));
    }
}

如上在父类的CONTROLLER中的构造函数使用中间件方法给对象属性设置值,在子类的CONTROLLER中有的时候获取不到设置的属性值

@dafa168
Copy link

dafa168 commented Feb 14, 2022

这种方式只能在fpm模式下玩起来, 常驻内存的模式必须把当前控制器销毁。
建议在具体的中间件文件handle中把参数设置到本次请求的request中,这样就能全局使用了,或者使用trait去获取.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants