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.
More such advice. Thank you.
Simple + Brilliant = Laravel
Cheers
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!
Hi Peter,
Of course, there is a way, but I guess that would be more complex custom code, not just relationship like here.
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
Hi, Murtaza Bharmal
You also can apply the above method like
File app/User.php
public function latestLog()
{
return $this->hasOne(‘\App\Log’)->latest();
}
and can use in the controller in the same way as described above in the post.
Ugh, I wish I know this several months ago