Eloquent: Get the Latest Row from Relationship

Another "hidden gem" of Eloquent. Let's imagine that you want to query all rows from the table and also one related row - not all of them, but the newest one. Apparently, it's pretty easy. Let's take a real-life example. Let's say we have Authors and Books, with 1-n relationship, so every author can have one or more books. And we want to show all Authors and their latest Book. Step 1. File app/Author.php - new method:
    public function latestBook()
    {
        return $this->hasOne('\App\Book')->latest();
    }
Method latest() orders all rows by created_at desc, and takes the first one. Step 2. Controller:
    $authors = Author::with('latestBook')->get();
    foreach ($authors as $author) {
        echo $author->name . ': ' . $author->latestBook->title;
    }
Also, you can use oldest() instead of latest() - then it would take the first record with rule order by created_at asc.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

You might also like