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

TxNuno's avatar
Level 13

Reuse Query

I've created this simple query.

$models = Model::whereBetween('created_at', [$start, $end])

and I am trying to use it for several things. For example, I am getting the total count with

$models->count() // 20` and the total amount with  `$models->sum('amount') // 50

I am then trying to filter the query for each date in an array and this is where I am having problems.

Running this query

$models->whereDate('created_at', '2018-07-24')->get()

returns all records for this day correctly but if I try to run another query for example

$models->whereDate('created_at', '2018-07-25')->get()

I get 0. It seems like I am modifying the initial query and once modified I am unable to use the $models variable for anything else as it now holds all of the data from the

$models->whereDate('created_at', '2018-07-24')->get() query.

What am I doing wrong? Can someone explain how I can use the initial query several times?

0 likes
1 reply

Please or to participate in this conversation.