Hello Devs,
In this tutorial, we will learn Laravel latest() and oldest() Eloquent Query Example
The latest and oldest methods allow you to easily order results by table column.
Follow this step by step guide below.
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 1 : 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 2 : 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);
}
May this example help you.