ozmnow's avatar

How does Auth::user()->name and Auth::user()->email work

I have a blade view for logged in users

To display my users name and email I do this

<p>{{ Auth::user()->name }}</p><br>

<p>{{ Auth::user()->email }}</p>

But what happens in the backround?

Does Laravel do two querys? One to fetch the users name and one to fetch the email? I just wonder if I should contionue to do like the above code or just fetch alla data in need in the controller with one query.

0 likes
6 replies
ftrillo's avatar

Well, I don't know how it works internally exactly. But there's an easy way to check how many queries it runs.

Try running this code and then checking the log to see the queries made:

DB::enableQueryLog();
Auth::user()->name;
Auth::user()->email;
Log::info(DB::getQueryLog());

Let me know what you find out. And if anyone is more savvy about the Auth implementation details, please share.

ftrillo's avatar

@edoc I think He's just wondering if calling Auth::user() more than once will query the database to get the user again and again.

sutherland's avatar

It will only query once. This is the query used when I try it out myself:

SELECT * FROM `users` WHERE `id` = '1' LIMIT 1
1 like
Snapey's avatar

Auth loads the record when the user is authenticated, so its not doing it in response to either of your blade tags. It can then use the loaded model for all logged-in user queries.

1 like
sutherland's avatar

@Snapey I tested it myself, and there is no query on the users table (at least according to Clockwork) unless you have one or more reference to Auth::user(), and then it is only queried once.

1 like

Please or to participate in this conversation.