I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Get latest row using Laravel?

It appear I am not getting latest row when rows have actually same created_at value.

Using $model->latest()->first() - I am getting first row rather than last row of created_at.

How to solve this?

Upvotes: 3

Views: 1452

Answers (2)

Giovanni S
Giovanni S

Reputation: 2110

latest() will use the created_at column by default.

If all of your created_at values are the exact same, this obviously won't work...

You can pass a column name to latest() to tell it to sort by that column instead.

You can try:

$model->latest('id')->first();

This assumes you have an incrementing id column.

Upvotes: 3

Jason
Jason

Reputation: 3030

This will entirely depend on what other data you have in your table. Any query of a relational database does not take the "physical position" into account - that is, there is no such thing as being able to get the "last inserted row" of a table until you are able check some value in the table that indicates it is the probably the last row.

One of the common ways to do this is to have a auto-incrementing unique key in the database (often the Primary Key), and you can simply get the largest value in that set. It's not guaranteed to be the last row inserted, but for most applications this is usually true.

What you need is the equivalent query to be executed

SELECT * FROM Table WHERE created_at = ? ORDER BY ID DESC LIMIT 1

or, in Eloquent ORM

$model->where('created_at', '=', ?)->orderBy('id', 'desc')->take(1)->first();

Keep in mind that you'll probably need other filters, since it is entirely possible other users or processes may insert records at the same time generating the same creation date, and you'll end up with somebody elses records.

Upvotes: 2

Related Questions