auth()->user() is returning null Hi !
In a Model file (/app/Models/xxx.php) I'm trying to get my logged-in user info:
$user = auth()->user();
logger($user);
This returns null, but I'm 100% sure my user is logged in.
This is working in other parts of the application I'm working on, but not here, and I really don't understand why.
I have read that sometimes it's due to the fact that you are in a __construct() method, but here it's not the case : It's a method called getCustomSmtp (if that can help..).
I also tried $user = Auth::user(); with the same result.
Any idea?
If auth()->user() is returning null, it means that the user is not authenticated. Here are some possible solutions:
Make sure that the user is actually logged in. You can check this by using the auth()->check() method. For example:
if (auth()->check()) {
$user = auth()->user();
logger($user);
} else {
logger('User is not authenticated');
}
Make sure that the route or controller method where you are calling auth()->user() is protected by the auth middleware. For example:
Route::get('/dashboard', function () {
$user = auth()->user();
logger($user);
})->middleware('auth');
If you are using a custom guard, make sure that you are specifying it when calling auth()->user(). For example:
$user = auth('admin')->user();
logger($user);
If you are using a multi-auth setup, make sure that you are specifying the correct guard when calling auth()->user(). For example:
$user = auth()->guard('api')->user();
logger($user);
Not really a good idea to have this in a model as a model might be used in many contexts where there is no authenticated user, eg
queued jobs
console commands
scheduler tasks
Better to pass in the authenticated user when you need to use this function.
Out of interest, this is not inside a queued email is it?
@Snapey Thank you so much. I was inside a queued job without knowing it (as you can guess, I'm a beginner).
So my problem is solved, I got the user from another object that contains the user's information.
@Alex -a mark best answer ?
Please sign in or create an account to participate in this conversation.