Select Last Row in the Table

Carlos Suñol picture Carlos Suñol · May 14, 2013 · Viewed 338.5k times · Source

I would like to retrieve the last file inserted into my table. I know that the method first() exists and provides you with the first file in the table but I don't know how to get the last insert.

Answer

Joachim Isaksson picture Joachim Isaksson · May 14, 2013

You'll need to order by the same field you're ordering by now, but descending. As an example, if you have a time stamp when the upload was done called upload_time, you'd do something like this;

For Pre-Laravel 4

return DB::table('files')->order_by('upload_time', 'desc')->first();

For Laravel 4 and onwards

return DB::table('files')->orderBy('upload_time', 'desc')->first();

For Laravel 5.7 and onwards

return DB::table('files')->latest('upload_time')->first();

This will order the rows in the files table by upload time, descending order, and take the first one. This will be the latest uploaded file.