How to get posts by year in Laravel

Categorized as Laravel Tagged

To get your latest posts ordered by year, you can use groupBy in your query. See the example below:

// Controller

$years = Post::query()
      fn($post) => $post->created_at->year

return vew('posts',['years' => $years]);
// View

@foreach ($years as $year => $posts)

  <h2>{{ $year }}</h2>

  @foreach ($posts as $post)

    <p>{{ $post->title }}</p>



Leave a reply

Your email address will not be published. Required fields are marked *