2

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')
....
Furkan ozturk
  • 654
  • 8
  • 26

2 Answers2

1

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();
Sammitch
  • 30,782
  • 7
  • 50
  • 77
STA
  • 30,729
  • 8
  • 45
  • 59
1

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');
zeref
  • 146
  • 2
  • 8
  • created_at is a date column, so you don't need to ->format(), you can directly pass the Carbon instances. – KyleK Jun 18 '20 at 10:02