While working with relationships, sometimes we need to get the first data of many to many relations or the latest data from one relationship where can be more than one record can exist. In this tutorial, we will see some examples to get the latest record from the relationship in Laravel.
Here, we will take an example where we have created two models Author and Book. We will apply logic to get the latest book using different methods. Before starting let’s create a relation into the Author model which will establish a relation to get one record:
public function book()
{
return $this->hasOne(Book::class);
}
The above relation will get a single record using author_id column from the books table. It will return only one record even if there are many records for the same author.
But here, we need to fetch the latest record of the book. So let’s modify or create a new one like below example:
public function latestBook()
{
return $this->hasOne(Book::class)->latest();
}
The above code will fetch one book but use timestamp value to get the latest book. Let’s see how to retrieve data using this relation:
$authors = Author::with('latestBook')->get();
foreach ($authors as $author) {
echo $author->latestBook->name;
}
We can also use the previous relation function with or without eager loading. But in this method, we need to add the latest() method while calling the relationship.
$authors = Author::get();
foreach ($authors as $author) {
echo $author->book()->latest()->name;
}
//or
$authors = Author::with(['book'=> function($quer){
$query->latest()->first();
}])->get();
foreach ($authors as $author) {
echo $author->book->name;
}
The first example will perform an additional query for getting the latest record using book relation while in the second example, we will apply the same logic by using eager loading. which will solve N + 1 query issue.
In this article, we have seen some examples to get the single latest record from the relationship. Those examples have only one-to-one relationships however you use this concept with any other types of relationships too.