search

Home  >  Q&A  >  body text

Select the last row in the table

I want to retrieve the last file inserted into my table. I know the method first() exists and gives you the first file in the table, but I don't know how to get the last insert.

P粉986028039P粉986028039430 days ago522

reply all(2)I'll reply

  • P粉020085599

    P粉0200855992023-10-12 07:17:19

    Use the latest scopes provided by Laravel out of the box.

    Model::latest()->first();

    This way you won't retrieve all records. Better shortcut for orderBy.

    reply
    0
  • P粉933003350

    P粉9330033502023-10-12 00:49:07

    You need to sort by the same fields as you are sorting now, but in descending order. For example, if you have a timestamp called upload_time when the upload is complete, you can do the following;

    For versions prior to Laravel 4

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

    For Laravel 4 and above

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

    For Laravel 5.7 and above

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

    This will sort the rows in the file table by upload time, descending , and take the first one. This will be the most recently uploaded file.

    reply
    0
  • Cancelreply