Fetch latest posts for each category

Submitted by mercuryseries - 9 years ago

If we have a blog, sometimes we want to display all latest posts by category. Take an example with this website where I put those posts in a carousel on the homepage: http://dadack.com

//Grab all categories
$categories = Category::all();

//This array will contain our result
$latest_posts_by_category = [];

//We use this array to save each post id that we have already collected
//in order to avoid to put it twice.
//Remember that some posts may belongs to  many categories.
$ids = [];

//For each category we grab the latest post with the latest first associated category
//(Note that you can collect all associated categories if you want by removing the first() in the closure)
foreach($categories as $category){
            
    $post = Post::with(['categories' => function($query){
                $query->latest()->first();
            }])
            ->online() //You may have a custom method like this.
            ->latest()
            ->whereHas('categories', function($query) use($category) {
                $query->whereName($category->name);
            })->take(1)->first();

    //We take in account the fact that 
    //some posts may belongs to many categories.
    //Obviously, we don't want to put it twice
    if(!in_array($post->id, $ids)){
        $latest_posts_by_category[] = $post;
        $ids[] = $post->id;
    }
}

//You can now use $latest_posts_by_category as you want