Please try like this:
$res = ModelName::where('someColumn', 'test')
->get()
->groupBy(function ($val) {
return Carbon::parse($val->created_at)->format('Y');
});
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi guys,
I'm in the process of developing a page which will show the records group by Year (the year will be part of a date field in mySql).
So I will have the year 2018 and below all the records selected where the year of the date field is 2018 then 2017 and so on according to the year available (some year might skip)
I'd like to know what would be the best practice to obtain something like this. Do I have to group the records by Year or simply select the record and then in the View manipulate the object in order to obtain the result? I think I could do it in a very "rustic" way I'm quite confident that there are some techniques in Laravel/Model that could make the entire process much more elegant.
Thanks a lot
@P81CFM - The answer by @cms007 grouped your results by year so it should already be in the format you want...you may just need to change your loop to this:
@foreach ($res as $year => $news)
<h1>{{ $year }}</h1>
<table>
@foreach ($news as $article)
<tr><td>{{ $article->title_slug }}</td></tr>
@endforeach
</table>
@endforeach
Please or to participate in this conversation.