Have you ever wanted to create a custom calendar in your PHP code but weren’t sure how to approach it? How do you consider the differences in the length of each month?

{ $startOfMonth = CarbonImmutable::create($year, $month, 1); $endOfMonth = $startOfMonth->endOfMonth(); return [ 'year' => $startOfMonth->year, 'month' => $startOfMonth->format('F'), + 'dates' => $startOfMonth->toPeriod($endOfMonth), ]; Now, we want to convert our CarbonPeriod instance into an array and map over it.

{ $startOfMonth = CarbonImmutable::create($year, $month, 1); $endOfMonth = $startOfMonth->endOfMonth(); return [ 'year' => $startOfMonth->year, 'month' => $startOfMonth->format('F'), - 'dates' => $startOfMonth->toPeriod($endOfMonth), + 'dates' => return collect($startOfMonth->toPeriod($endOfMonth)->toArray()) + ->map(fn ($date) => [ + 'path' => $date->format('/Y/m/d'), + 'day' => $date->day, + ]), ]; That’s a good start, but since we want to render these day numbers in a month view, we need to split the dates so there are chunks of exactly seven days for each week.

{ $startOfMonth = CarbonImmutable::create($year, $month, 1); $endOfMonth = $startOfMonth->endOfMonth(); - $startOfWeek = $startOfMonth->startOfWeek(); - $endOfWeek = $endOfMonth->endOfWeek(); + $startOfWeek = $startOfMonth->startOfWeek(Carbon::SUNDAY); + $endOfWeek = $endOfMonth->endOfWeek(Carbon::SATURDAY); return [ 'year' => $startOfMonth->year, 'month' => $startOfMonth->format('F'), 'dates' => return collect($startOfWeek->toPeriod($endOfWeek)->toArray()) ->map(fn ($date) => [ 'path' => $date->format('/Y/m/d'), 'day' => $date->day, ]), ]; Now that we know our CarbonPeriod instance and the resulting collection contain a number of items that’s a multiple of seven, we can use the Collection chunk method to split the array into nested arrays with seven items each.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners