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

blader4o's avatar

Include min max in pagination count query

Hey guys first time I ask something here.

I have the following problem - I see, when I use the paginate() method on my eloquent models, Laravel makes 2 queries - a count query and select one.

My goal is to get the min and max values in table for a specific column. Is there a way to add select min(),max() in the count query or I have to make a separate one.

Thanks

0 likes
7 replies
Snapey's avatar

It would need a separate query.

Tray2's avatar

Is it something like this you are looking for?

SELECT count(*), min(field), max(field)
FROM table;
blader4o's avatar

I'm talking about the laravel paginate() method.So for example

$products_q = Product::where('active',1); // sets the where 
$products = $products_q->paginate(20); // this line here makes 2 requests:
# SELECT COUNT(*) FROM products WHERE active=1
#and
#SELECT * FROM products WHERE active=1 LIMIT  0,20;

My question is can I add somehow Min and Max in the first query with the paginate() method in laravel so the first query becomes like this :

SELECT COUNT(*),MIN(price) as min_price, MAX(price) as max_price FROM products WHERE active=1
Tray2's avatar

You can always do

$products->max('price');
$products->min('price');

but that is only on the selected 20.

or you can have a method maxPrice in your products model.

public function maxPrice()
{
 return Product::where('active', 1)->max('price');
}
blader4o's avatar

This will aggregate the whole table result and give me only 1 row. I want aggregated results as well as the listing. Please read the question. It's specific with the paginate() method

Tray2's avatar

Then use db::select and write it in plain SQL.

DB::select('SELECT *, max(price) max_price, min(price) min_price, (SELECT count(*) FROM products WHERE active = 1) quantity FROM products offset = :offset and limit = 20', ['offset' => $offset]);

or somesuch.

Snapey's avatar

why are you sweating it? Just write an extra query and cache the result so that you dont need to do it on page2,3 etc

How would you do it if you didnt use pagination? You would need an extra query because what you want is an aggregation and that cannot be in the same query as pulling the table

Please or to participate in this conversation.