Skip to content

Instantly share code, notes, and snippets.

@webrobert
Last active February 3, 2023 00:20
Show Gist options
  • Select an option

  • Save webrobert/918fa1767221e49772e14bdb93109612 to your computer and use it in GitHub Desktop.

Select an option

Save webrobert/918fa1767221e49772e14bdb93109612 to your computer and use it in GitHub Desktop.
Calendar with Carbon and pad()

When I’ve got some time I like to read Helpers and Collections in the laravel docs.

Partly because I’m a geek and partly because it seems like sometimes I don’t get it until I have a use case.

Recently I wanted to render a calendar. I found a use for two new methods times() which skips the need for collecting a range and pad() to continue rendering elements in a blade loop even when empty. Or in this first example. It let me create empty days for the start of the month (based on the day of week a month starts)...

// Carbon $date
$startDay = (int) $date->firstOfMonth()->isoFormat('d');
$daysWithOffset = $date->daysInMonth + $startDay;
        
$days = Collection::times($date->daysInMonth, fn($day) => match(true) {

    // do stuff the $day variable is the index starting at 1
    
})->pad("-$daysWithOffset", null);

Screenshot.png

All this was great in the loop until there were not enough days to complete the last week (row) in the table.

@foreach($days->chunk(7) as $week)
    <tr>
        @foreach($week->pad(7, null) as $day)
            <td class="border border-slate-200">
              
              {{-- doing more cool stuff --}}
            
            </td>
        @endforeach
    </tr>
@endforeach

pad let me declare 7 elements even when their were only 2 days in the last week of the month.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment