【笔记】Laravel 中__construct 无法获取 Auth::user () 信息无法共享 user 数据的解决办法

Laravel ⋅ tytrock ⋅ at 2023-05-16 14:08:29 ⋅ 4912 Reads

Laravel5.3+以后__construct函数已无法获取Auth::user()信息了。

故想在__construct中共享Auth::user()的信息已变得不可行,例如下图所示

image.png


因Laravel框架加载流程 middleware执行总在__construct函数之后运行,故弄个middleware来解决该问题


1、创建一个middleware

class CheckAuth
{
    public function handle($request, Closure $next)
    {
        view()->share('user',Auth::user()); //将数据共享到视图上
        return $next($request);
    }
}


2、在Kernel中注册中间件

protected $routeMiddleware = [
        'checkAuth' => \App\Http\Middleware\CheckAuth::class,//定义的中间键
];


3、在构造函数中使用

$this->middleware('checkAuth');


This topic has been mark as Excenllent Topic.
Total Reply Count: 0
    No comments~~
    • publish_typography
    • publish_markdown
    • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
    • publish_image
    • publish_draft
    Ctrl+Enter