Selecting last inserted row from table in Laravel

We know first () is used to get the first file from the table. You need to use order by descending on the same field you want. For example, if you are trying to get the last created table by the order of created_at field.

In Laravel versions 4 use:

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

For Laravel 5 versions use:

User::orderBy('created_at', 'desc');

The problem with the above method is that sometimes when we are trying to get the order by some timestamp, there could be more than one rows with the same timestamp. In such cases, the below method can be used.

Files::orderBy(id', 'desc')->first();