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.

Like our articles?
Check out our Laravel online courses!

5 COMMENTS

  1. Hi,

    let’s say, there are also categories of books, like drama, horror, romance, etc. Is there a way, how you can get latest book of each category for given author?

    Thanks for advice!

  2. Hi,
    Can you please help me with below query?
    – I have users table and logs table (logs have multiple entries of single user)
    – I want all users with their latest log.
    How can I achieve this?
    Thanks in advance

LEAVE A REPLY

Please enter your comment!
Please enter your name here