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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community