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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners