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 forAuth::user()—both work, but the helper function is a bit cleaner.- Once you assign
$this->userin the closure, you can access it in any of your controller's methods like$this->user->idor$this->user->name. - If your controller requires authentication for all methods, you can combine this with the
authmiddleware 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

