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:
Above relation will get a single record using author_id column from 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:
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:
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.
The first example will perform an additional query for getting the latest record using book relation while in the second example, we will apply 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 relationship however you use this concept with any other types of relationships too.