volver's avatar

does First() get the oldest or latest item by default

Hello Guys. I was wondering if the Eloquent method ->first() returns the latest or oldest record by default. from my experiment it always gives me the oldest record but I just wanted to make sure if this is a consistent behavior

0 likes
2 replies
Snapey's avatar

first() gives you whatever record is at index 0 in the search results.

So if you use ->latest() then this is sorted by date and is the most recent

but if you use ->orderBy('name')->first() then first is the person with the first name in alphabetical order

So, NO, first does not give you the oldest or the latest. It gives you the first result.

kokoshneta's avatar

It’s neither – Eloquent\Builder::first() doesn’t know anything about latest or oldest records by itself. What it gets is the first record returned by the database.

In most cases, assuming you’re fetching from a table that adheres to standard Laravel schemes (e.g., has an auto-incrementing id column) without any ordering clauses, that will be the oldest record, since that’s the nature of auto-incrementing primary keys.

But there are various circumstances where you can end up with a database result set with no fixed order (e.g., if you’re fetching from a table with no primary key). In such cases, the order of records returned from the database may not be fixed or reliable, and first() would then also not be reliable – may even return different rows for multiple executions of the same query.

And of course, if you have any ordering clauses, those determine what row will be returned. If you order by primary key or created_at in descending order, you will get the latest result, not the oldest, for example, and if you sort by first_name or email, you’ll likely get a record that’s neither the newest nor the oldest.

Edit: Basically what @snapey said, just with more typing…

Please or to participate in this conversation.