Get latest record by created at in Laravel

You can get the latest record by using created_at column in Laravel with orderBy(), sortByDesc(), latest() method. There are lots of method available in Laravel to get the latest record from the table. You can use one of them to get the latest record from table in Laravel

Answers 1
  • Get latest record from users table using sortByDesc() method on created at column in Laravel

    $lastRecord = App\Models\User::all()->sortByDesc('created_at')->take(1)->toArray();
    return $lastRecord;
    
    0

    Output:

    {"12":{"id":19,"name":"w3codegenerator.com","email":"[email protected]","email_verified_at":"2021-09-24T03:36:45.000000Z",
    "created_at":"2021-10-17T03:36:45.000000Z","updated_at":"2021-09-24T03:36:45.000000Z"}}

    This code snippet get all the users records from users table and sort it by descending order and take first item from collection after sorting.

  • Back to code snippet queries related laravel