Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Farstone's avatar

Optimizing my Auth::User()->withCount()->with() query

Hi laravel community, i have a problem understanding the query i do to fetch some hasMany relations count. Actually to fetch relations count on my user i do the following query :

$user = Auth::user()->withCount('announces', 'events')->with('badges', 'votes', 'image')->where('id', Auth::id())->first();

First of all this query work just fine, but i get a verry new model instance from it wich isn't what i want.

There is 2 problem with this query, first i pass an existing model instance wich only serve as "wich Eloquent model to retrieve", so i need to specify the where to retrieve the actual Authenticated user, otherwise every user is fetched from the database wich is a waste of perf, actually, replacing the Auth::user() by User::find(Auth::id()) would do the exact same thing.

The second problem is that the User class instance informations is totally refreshed wich is also a little waste of performance, if i set a random ID before running the query it get updated, i would like to return the Auth::user() with the new query informations instead of refreshing it totally, wich is kinda related to the first problem. My question is, it is possible to use an existing model instance to help a query and updating only the withCount()->with() of this instance ? Why the query builder ins't able to understand that im actually pointing him the exact model to retrieve ? I hope it make sense with my average english skill. This is really not big of a deal but i found the Auth::user() useless in this case since it is not used at all for my query, wich is sad.

0 likes
4 replies
bobbybouwmann's avatar
Level 88

Well you can get around the refreshing of the user model by using load instead of with

$user = Auth::user()->load(['badges', 'votes', 'image']);
$user->badges;
$user->votes;

Documentation: https://laravel.com/docs/5.7/eloquent-relationships#lazy-eager-loading

There is currently no such thing for counts at the moment. However you can create a seperate relation for just the count and then you can include it using load. Check out this resource

Source: https://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/

This way your model shouldn't have to refresh at all ;)

1 like
staudenmeir's avatar

In addition, Laravel 5.8 will add a loadCount() method.

1 like
Farstone's avatar

Thanks for your answers, good to know that laravel 5.8 will include this feature but i don't know how easy is laravel to migrate from 5.7 to 5.8 we'll see. Actually by adding more feature to my project i now need to totally eager load the counts so it's not a problem anymore since i can load the relations and count the collection count.

Please or to participate in this conversation.