Search code examples
imagelaravelgroup-bylaravel-5laravel-5.3

Create Image Album Group By Month and Year and Show First Image of the Album


I am creating an Image Album Grouped by date,

In my Blog App, Every post has a featured Image and I want to create an album of an image that is group by Year and month and show the first image of the album as the album cover, I already grouped my post by date but the problem is I can't get the first image of the album to be the cover of the album

Here is how I grouped by blog post by date

$postdates = App\Post::select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count'))
            ->groupBy('year')
            ->groupBy('month')
            ->orderBy('year', 'desc')
            ->orderBy('month', 'desc')
            ->limit(12)
            ->get();
    ?>

and Here is how i get the Image the problem is I think in here

@foreach($postdates as $postdate)
   <li><a href="#"><img src="{{asset('images/'. $postdate->featured_image)}}" alt=""></a></li>
@endforeach

"featured_image" is the column of the table for the image names.


Solution

  • Already got it guys, thanks

     $postdates = App\Post::select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count, MIN(featured_image) as image'))
                ->groupBy('year')
                ->groupBy('month')
                ->orderBy('year', 'desc')
                ->orderBy('month', 'desc')
                ->limit(12)
                ->get();