Reputation: 722
I assume recording date of a user's the last activity as 13.04.2019 . I want to sum all records in the week belonging the last record.
ex:
created_at = 13.04.2019, activity = 3
created_at = 11.04.2019, activity = 3
created_at = 01.04.2019, activity = 3
//the above 3 records is not same week. I need last week to sum activites so the result of sum will be 6
How could I do this with Carbon or others
$sum_last_week = Model::where('user_id',$user->id)->orderby('id','desc')->sum('activity')
....
Upvotes: 2
Views: 555
Reputation: 166
First retrieve the last active date,
$model = Model::where('user_id', $user->id)->orderby('created_at',desc)->first();
Then, generate target range depending on above result
$testDate=$model->created_at;
$from = $testDate->startOfWeek()->format('Y-m-d H:i');
$to = $testDate->endOfWeek()->format('Y-m-d H:i');
Last, retrieve sum
$result =Model::whereBetween('created_at', [$from, $to])->sum('activity');
Upvotes: 1
Reputation: 34708
The whereBetween
method verifies that a column's value is between two values.
$from = date('Y-m-d',strtotime('-7 days'));
$to = date('Y-m-d');
$last_week = Model::whereBetween('created_at', [$from, $to])->get();
Upvotes: 1