Home > OS >  How to get missing dates between 7 latest rows from database?
How to get missing dates between 7 latest rows from database?

Time:12-22

I want to get 7 latest rows (in order from down to up), for the current week (Sunday to Saturday), for the current logged in user.

To do this, I used this one method:

Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
$strikes = UserStrike::where('user_id', $user)->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->latest()->take(7)->get();
$strikes = $strikes->reverse(); //to order the list from DESC to ASC

But the problem with this method is that it doesn't get any missing days.

So if there are data like this for the current week (2020-05-12 is missing):

created_at: 2020-05-10
created_at: 2020-05-11
created_at: 2020-05-13

Then for that one day which is missing, there should be a null in array. Something like this:

$days = ["Sun", "Mon", null, "Wed"];

I'm having hard time to find a way to replace missing day with a null in array.

If anyone here can help me with this problem please leave your comment. Thank you in advance.

CodePudding user response:

You can take data from DB and then create array by iterating on DateTimeInterval(). I don't know Laravel and Carbon well but it could be something like this:

Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);

$start = Carbon::now()->startOfWeek();
$end = Carbon::now()->endOfWeek();

$strikes = UserStrike::where('user_id', $user)
  ->whereBetween(
    'created_at', 
    [$start, $end]
  )
  ->latest()
  ->take(7)
  ->get();
$strikes = $strikes->reverse();

$timePeriod = new DatePeriod(
  $start,
  new DateInterval('P1D'),
  $end
 );

$days = []; 
for ($i = 0; $i < count($timePeriod) $i  ) {
  $days[$i] = null;
  foreach ($strikes as $strike) {
    if ($strike->created_at->format('Y-m-d') == $checkedDay->format('Y-m-d') {
      $days[$i] = $strike->created_at->format('Y-m-d');
      break;
    }
  }
}
  • Related