I have two models Post and Category
// migration post
public function up()
{
Schema::create(\'posts\', function (Blueprint $table) {
$ta
An Eloquent solution for loading categories with latest post is to create an additional hasOne() relationship in the Category model:
public function latestPost()
{
return $this->hasOne(Post::class)->latest();
}
And then use eager loading:
Category::with('latestPost')->get();
This will generate just 2 queries to DB.