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

motinska94's avatar

Does using limit() before pagination to optimize withSum method make sense?

I'm using ->withSum(['column1', 'column2']) method to get sum of selected columns from multiple rows in the table. I was wondering if I can use ->limit($paginate_count) before withSum() and paginate() methods to optimize the speed a little. Does this make sense?

I added it to my command and nothing much changed, or at least it didnt break 😅

I just wanted to ask if this makes sense or is it unnecessary and laravel already gets the sums after doing the pagination.

Example code :

$customers = Customer::select(['id', 'name', 'contact'])
            ->where('address', 'like', '%' . $search_word . '%')
            ->orWhere('contact', 'like', '%' . $search_word . '%')
            ->orWhere('name', 'like', '%' . $search_word . '%')
            ->orderBy('created_at', 'desc')
            ->limit($this->paginate_count)
            ->withSum('sales', 'price_paid')
            ->paginate($this->paginate_count)
            ->appends(request()->query());
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You are just adding limit twice. It makes absolutely no difference

1 like
motinska94's avatar

@Sinnbeck Thanks! I was worried because since withSum sums multiple rows in the table and I'm using paginate after that line, I thought it gets all the records' sums and then paginates(limits) it. 😅 Better safe than sorry I guess.

Please or to participate in this conversation.