Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

edres's avatar
Level 1

difference between latest() and first()

what is difference between latest() and first() ? i would be very appreciated if you could help me

0 likes
4 replies
bicicura's avatar

Straight from the docs!

LATEST: The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the table's created_at column. Or, you may pass the column name that you wish to sort by.

FIRST: If you just need to retrieve a single row from a database table, you may use the DB facade's first method.

https://laravel.com/docs/9.x/queries

3 likes
tykus's avatar

latest() is an alias for orderBy('created_at', 'desc') - although you can specify a different ordering column name.

first() gets the first Model record that satisfies the preceding query.

So you would never complete a query with latest because it returns a Builder instance - it doesn't actually execute a query as first, find, get etc, will

5 likes
okusax's avatar
okusax
Best Answer
Level 6

hi @edres In a collection context $collection. When you create a collection of objects all the items are inserted in an specific order (usually order by id but you can change it).

If you use $collection->first() you would get the object on the first position of that collection. The same goes for last() but getting the last one.

When you make an Eloquent query you always get a collection of models (or only one if you use find()). Anyway You can end your statement with first() to get 1 object (that object would be the first of the query result, if you sort asc your query by id, it would be the one with the smaller id that comply with the where conditions, or if you sort desc it would be the one with the bigger id). last() is not available as an Eloquent function but you can use first() and sort options to archive it.

For example, imagine that you have a User model with an age property:

$first_user_that_match = User::where('age', '>=', '18')->first();

With that query you are getting a collection of users with age >= 18 and staying with the first one in $first_user_that_match , doesn't matter which, the order result will determine what model would be.

1 like

Please or to participate in this conversation.