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

farshadf's avatar

chunking huge query with withcount and orderby

i have a pretty heavy query that hits the memory limit and return 500 error here is the query :

       $collection = User::with('city')
            ->withCount('userReferral')
            ->orderByDesc('user_referral_count')
            ->get();

        $data  = $collection->where('username', $userName);

this is for a ranking that shows the user rank on the ranking of the users based on the count of user she/he invited to site . this now returns 500 on server which is because of memory limit which i dont want it to consume that amount of memory . how can i rewrite this with chunk so it consume less memory ??

0 likes
7 replies
wingly's avatar

Well why don't you do the where directly at the query? Is there a reason ?

       $data = User::with('city')
		->where('username', $userName)
            ->withCount('userReferral')
            ->orderByDesc('user_referral_count')
            ->get();
farshadf's avatar

@wingly no and i tried the directly in query way too it again hits memory limit

MichalOravec's avatar

If you need to work with collection you can use Lazy Collections. What is it your memory limit? Just increase your memory limi in php.ini

For example

memory_limit = 2048M
farshadf's avatar

256mb on server and i have been told that it cant be increased a lot due to high load on server and the query is being lunched on like 50k users . is that amount really alot for that ram ???

wingly's avatar

Isn't this User::with('city')->where('username', $userName) supposed to return you one user ?

MichalOravec's avatar

So you can use chunk but propably if you need create array of that count users, you will need change server where they allow you to increase memory limit higher than 256MB.

farshadf's avatar

it counts the relation that this model has which is the user referal that it shows the number of people user invited to site

Please or to participate in this conversation.