Laravel eloquent get the latest row of related table
Because relationships are separate queries, you can't add a limit to an eager loaded relationship. If you do, this limits the entire relationship query, it does not act as a limit per related object.
Luckily, your requirement can be implemented simply with an additional relationship:
public function latestChapter() { return $this->hasOne(Chapter::class)->latest();}
Now, instead of eager loading the entire chapters
relationship, you can just eager load your new latestChapter
relationship.
$books = Book::with(['authors', 'categories', 'latestChapter'])->get();
I know it is an old post, but there are some new solutions and I want to share it with you.In laravel 8, there are new helper functions: latestOfMany , oldestOfMany and ofMany.For your example, you could use:
public function latestChapter() { return $this->hasOne(Chapter::class)->latestOfMany();}
For those who are not able to upgrade laravel 8.4 to have ->latestOfMany
method, hasOne
relation can be enhanced with a self join to filter out latest related model per each main model
public function lastchapter(){ return $this->hasOne(Chapter::class)->join(DB::raw("( SELECT MAX(id) as id, book_id FROM `books` as `books_sub` GROUP BY book_id ) as lastchapters"), function ($join) { $join->on("lastchapters.id", '=', "books.id"); })->whereRaw('lastchapters.id = books.id');}