[Chartjs]-Laravel chartjs dates skipped

1๐Ÿ‘

โœ…

I assumed your created_at column is timestamp (formatting added for that case)

public function index()
{
    $start = Carbon::today()->subDays(7);
    $end = Carbon::yesterday();

    $activities = Activity::where('member_id', Auth::user()->id)
        ->where('created_at', '>=', Carbon::today()->subDays(7))
        ->get(['bonus', DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d') as date")])
        ->pluck('bonus', 'date');

    $dates = $this->generateDates($start, $end); // you fill zero valued dates

    return $dates->merge($activities); // overwrite your bonuses with the zero values
}

public function generateDates(Carbon $startDate, Carbon $endDate, $format = 'Y-m-d')
{
    $dates = collect();
    $startDate = $startDate->copy();

    for ($date = $startDate; $date->lte($endDate); $date->addDay()) {
        $dates->put($date->format($format), 0);
    }

    return $dates;
}

to format dates

$formattedDates = $dates->merge($activities)
            ->keys()
            ->transform(function ($date) {
                return Carbon::parse($date)->format('d F');
            });

Leave a comment