You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6.*中如何在构造方法中获取已登录用户?

How to Get Authenticated User in Controller Constructor (Laravel 5.6)

Hey there! I totally get why you're stuck here—Laravel changed how session and authentication work in constructors starting from 5.3, which can be confusing at first. Let's break down the solution step by step.

Why Your Original Code Didn't Work

In Laravel 5.3+, the authentication middleware doesn't run before the controller constructor by default. That means when you tried to call $this->user->Auth::user()->id; (also note the syntax error here—should be Auth::user()->id without the $this->user-> part), the session wasn't initialized yet, so there was no authenticated user to fetch.

The Correct Approach: Use a Middleware Closure

To access the authenticated user in your constructor, you need to wrap the user retrieval logic inside a middleware closure. This closure runs after the authentication middleware has processed the request, so the user will be available.

Here's how to implement it:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        // Assign the authenticated user to the controller's $user property
        $this->user = auth()->user();
        
        // If you just need the user ID directly, you can use:
        // $userId = auth()->id();
        
        return $next($request);
    });
}

Key Notes:

  • auth()->user() is a shortcut for Auth::user()—both work, but the helper function is a bit cleaner.
  • Once you assign $this->user in the closure, you can access it in any of your controller's methods like $this->user->id or $this->user->name.
  • If your controller requires authentication for all methods, you can combine this with the auth middleware to ensure only logged-in users can access the controller:
    public function __construct()
    {
        $this->middleware('auth')->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
    }
    

That should solve your problem! You'll now be able to access the authenticated user in your controller's constructor without issues.

内容的提问来源于stack exchange,提问作者Gabriel Meireles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:59:36