1

If I retrieve a model/collection in a controller and have the same call in a following event, will Laravel reuse the model/collection from the controller or fetch the data with a second database call?

Thanks in advance!

Edit: I refer to a call like this:

User::where('user_id', 42)->first();
Frooplet
  • 198
  • 1
  • 1
  • 8

1 Answers1

1

If you do $user = User::where('user_id', 42)->first();

Then reuse $user in the later code, then it will reuse it because you are using a variable.

But every time you make a call like User::where('user_id', 42)->first();, that does directly trigger a new database call. So, the answer to your question is no, it won't 'reuse' it, unless you use a variable, and don't make the eloquent call the second time.

Since you're asking this question, there are a couple of other things you might be thinking of; one is caching, another is eager loading, which is a slightly different thing, to do with loading related models onto the actual model that makes up the call; yet another us Auth::user(), but that's not the example you've given above with User:: so I assume you didn't mean that.

mwal
  • 2,803
  • 26
  • 34
  • Thank you, thats's exactly what I wanted to know! How does Auth::user() behave differently? – Frooplet Mar 25 '18 at 18:47
  • 1
    Glad to help. AFAIK it should be possible for laravel to do the Auth::user() query only once per request, i.e. internally cache it, even if it's called multiple times (since the authenticated user cannot change during a single request..), but it's such a low impact query that I haven't actually ever tracked down whether laravel in fact does that or not. I wouldn't worry about it personally. The authors of the framework know what they are doing :) – mwal Mar 25 '18 at 19:28
  • 1
    Answer here: https://stackoverflow.com/questions/29566182/does-laravel-query-database-each-time-i-call-authuser – mwal Mar 25 '18 at 19:35