Frooplet
Frooplet

Reputation: 208

Does Laravel reuse models?

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();

Upvotes: 1

Views: 517

Answers (1)

mwal
mwal

Reputation: 3103

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.

Upvotes: 1

Related Questions