One way to group members by year in Laravel is to use the groupBy()
method on a collection of members, with the year
method on a date attribute as the grouping key. Assuming the members have a created_at
attribute:
// Get all members
$members = Member::all();
// Group members by year
$membersByYear = $members->groupBy(function ($member) {
return $member->created_at->year;
});
This will create a new collection where each item represents a year, with the value being a collection of members created in that year. To output the results, you can loop through each year and its associated members, for example:
@foreach ($membersByYear as $year => $members)
<h2>{{ $year }}</h2>
<ul>
@foreach ($members as $member)
<li>{{ $member->name }}</li>
@endforeach
</ul>
@endforeach
Asked: 2023-05-08 16:14:11 +0000
Seen: 7 times
Last updated: May 08 '23