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

CItyTrader's avatar

Filter a collection in a range of values

I am trying to filter a collection by date. I am not filtering from the database directly. How can I get $tripLastWeek pls

$reports = collect([]);

 $users = User::with(['driverTrip' => function ($query) {
            return $query->select(['driverId', 'tripAmt', 'created_at']);
        }])->where(['userType' => 'driver', 'isAvailable' => 'online'])->whereHas('driverTrip', function ($query) {
            $query->whereNotNull('tripAmt')->where(['tripRequest' => 'approved']);
        })->get(['id', 'name']);


 $previous_week = strtotime("-1 week +1 day");
        $start_week = strtotime("last sunday midnight", $previous_week);
        $end_week = strtotime("next saturday", $start_week);
        $start_week = date("Y-m-d", $start_week);
        $end_week = date("Y-m-d", $end_week);


foreach ($users as $user) {

	$tripToday = $user->driverTrip->filter(function ($query) {
                return date('Y-m-d', $query->created_at->timestamp) == date('Y-m-d');
            });
	$tripLastWeek = $user->driverTrip->filter(function ($query) {
                return $query->whereBetween()
            });

 	 $reports->put($user->id, [
                'driverName' => $user->name,
                'tripAmt' => $user->driverTrip->sum("tripAmt"),
                'tripCount' => $user->driverTrip->count('tripAmt'),
                'tripAmtDay' => $tripToday->pluck('tripAmt')->sum(),
                'tripAmtCount' => $tripToday->count(),
                'tripAmtLastWeek' => $tripLastWeek->pluck('tripAmt')->sum(),
                'tripAmtLastWeekCount' => $tripLastWeek->count()

            ]);
}
0 likes
1 reply
Dunsti's avatar

I would do it like this:

->whereBetween( now()->subDays(7)->toDateString(), now()->toDateString() )

Please or to participate in this conversation.