Skip to main content
Tutorial Free

Eloquent: Get the Latest Row from Relationship

January 23, 2017
1 min read
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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

No comments yet…