Reputation: 133
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
Upvotes: 1
Views: 294
Reputation: 522732
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.
Upvotes: 2