To begin the investigation, can you check what your obtain ?
$data = $this->getData();
dd($data);
$this_week = $this->getWeekly($data);
dd($data);
$last_week = $this->getWeekly($data, 1);
dd($data);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm using this logic to get sales from this week and last week. I added a $minus value to substract number of weeks from the query in getWeekly method. And I'm only using getData() to broadly filter my data in order to re-use it by calling and saving it once.
However, this code only runs once and it breaks after first run. I can switch $this_week and $last_week's places and no matter what, the first one I declared runs fine but other one returns [].
I noticed something weird on the clockwork extension.

After running the first query, whereRaw data sticks around and gets into the second query as well. And since a record can't be in 2 different weeks at once, it returns empty.
Anyone have any idea why this is happening? It seems so weird, I'm not even updating the $data variable.
My Controller :
public function index()
{
$data = $this->getData();
$this_week = $this->getWeekly($data);
$last_week = $this->getWeekly($data, 1);
return view('employee.stats.index', compact('this_week', 'last_week'));
}
public function getData()
{
return Sales::query()
->whereStoreId(Auth::user()->store_id)
->whereYear('created_at', '>=', date('Y') - 1)
->where('status', '>', '1')
->orderBy('created_at');
}
public function getWeekly($data, $minus = 0)
{
$week = date('W') - $minus;
$select_week = $data->whereYear('created_at', '=', date('Y'))->whereRaw('WEEK(created_at) = ' . $week)->get();
$select_day = $select_week->groupBy(fn($item) => $item->created_at->format('D'));
$returnArray = [];
foreach ($select_day as $day)
{
$total = 0;
foreach ($day as $sale)
{
$total += $sale->price_total;
}
$returnArray[$day->first()->created_at->format('D')] = bcdiv($total, 1, 2);
}
return json_encode($returnArray);
}
Using it this way works, but then what's the point of even using $data...
$data = $this->getData();
$this_week = $this->getWeekly($data);
$data = $this->getData();
$last_week = $this->getWeekly($data, 1);
If you're passing the $data query builder instance around then you can't apply a whereRaw on it and then expect it to disappear the next time you use that instance. Different queries need different instances.
Remember, objects are passed by 'reference' and not value. You can clone the instance before you apply the whereRaw on it if desired:
$dataClone = clone $data;
You're right in that there's no point in the $data variable, you should just use this instead (and consider renaming your methods):
$this_week = $this->getWeekly($this->getData());
$last_week = $this->getWeekly($this->getData(), 1);
Please or to participate in this conversation.