Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

An example:

//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 remove 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
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

dhatch6 dhatch6 Joined 9 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.