latest() and oldest() Eloquent Query in Laravel Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this blog, I will show you how we can get latest and also get oldest record from our database. The latest and oldest methods are allow us to easily order results by the table column.

So by default, result will be ordered by the created_at column. So if we will pass the column name that we wish to sort by by using orderBy method.

So here I will give you four example for latest() and oldest() method as bellow.

Example 1 : latest() eloquent
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function getLatestRecord()
{
    $latests = User::latest()->get();

    dd($latests);
}

Output

array:4 [
  0 => array:3 [
    "name" => "keval"
    "email" => "keval@gmail.com"
    "created_at" => "2019-12-26 00:00:00"
  ]
  1 => array:3 [
    "name" => "piyush"
    "email" => "piyush@gmail.com"
    "created_at" => "2019-12-25 00:00:00"
  ]
  2 => array:3 [
    "name" => "savan"
    "email" => "sava@gmail.com"
    "created_at" => "2019-12-09 00:00:00"
  ]
  3 => array:3 [
    "name" => "mehul"
    "email" => "mehul@gmail.com"
    "created_at" => "2019-12-01 00:00:00"
  ]
]
Example 2 : OrderBy with latest eloquent
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function getLatestRecord()
{
    $latests = \DB::table('users')->orderBy('created_at','desc')->get();

    dd($latests);
}
Example 3 : oldest() eloquent
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function getOldestRecord()
{
    $oldest = User::oldest()->get();

    dd($oldest);
    
}

Output

array:4 [
  0 => array:3 [
    "name" => "mehul"
    "email" => "mehul@gmail.com"
    "created_at" => "2019-12-01 00:00:00"
  ]
  1 => array:3 [
    "name" => "savan"
    "email" => "sava@gmail.com"
    "created_at" => "2019-12-09 00:00:00"
  ]
  2 => array:3 [
    "name" => "piyush"
    "email" => "piyush@gmail.com"
    "created_at" => "2019-12-25 00:00:00"
  ]
  3 => array:3 [
    "name" => "keval"
    "email" => "keval@gmail.com"
    "created_at" => "2019-12-26 00:00:00"
  ]
]
Example 4 : OrderBy with oldest() eloquent
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function getOldestRecord()
{
    $oldest = \DB::table('users')->orderBy('created_at','asc')->get();

    dd($oldest);
}

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →