1
votes

I am using laravel and i need to retrieve the last row of my table. I'm using the code below but apparently it is getting the whole table and then looping to the last element . This would become an issue if the table is huge.

$result = Table::orderBy('created_at', 'desc')->first();

Is there a better , more efficient way to get the last row : Eloquent or sql query.

Thanks

1
Are you sure it will loop over everything? first() will create a query with the limit of one because it knows you only want one element.cre8

1 Answers

2
votes

Your current Laravel query is one way to find the most recent row of your database. As mentioned by @vladatr it corresponds to the following raw MySQL query:

SELECT * FROM yourTable ORDER BY created_at DESC LIMIT 1

To answer your question, one way to speed up this query at the MySQL level would be to add an index on the created_at column. This index, if used by the optimizer, should speed up the sorting operation needed to find the most recent record.