Laravel 5.3+ __construct 获取 Auth::user() 信息

佴涵蓄
2023-12-01

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

故我在做根据用户编号获取菜单信息时这步非常困难,现将解决解决方案写在下面。

因Laravel框架加载流程 middleware执行总在__construct函数之后运行,故$this->middleware(‘checkMenu’); 写在构造函数的哪个位置都会最后执行。

创建中间件

//在Middleware中创建类
class MenuCheck
{
    public function handle($request, Closure $next)
    {
        $user_id = Auth::user()->id;
        view()->share('menu',$user_id); //将数据共享到视图上
        return $next($request);
    }
}

//在Kernel中注册中间件

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'checkMenu' => \App\Http\Middleware\MenuCheck::class,//定义的中间键
    ];

构造函数中使用

 $this->middleware('checkMenu');
 类似资料: