Laravel latest() and oldest() Eloquent Query Example

Admin   Laravel   722  2021-03-16 12:10:07

Hi Guys,

In this blog, I will show you how to get latest and oldest record into the database. The latest and oldest methods allow you to easily order results by table column.

By default, result will be ordered by the created_at column. You will pass the column name that you wish to sort by using orderBy method.

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

Users Table

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" => "[email protected]"

"created_at" => "2019-12-26 00:00:00"

]

1 => array:3 [

"name" => "piyush"

"email" => "[email protected]"

"created_at" => "2019-12-25 00:00:00"

]

2 => array:3 [

"name" => "savan"

"email" => "[email protected]"

"created_at" => "2019-12-09 00:00:00"

]

3 => array:3 [

"name" => "mehul"

"email" => "[email protected]"

"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" => "[email protected]"

"created_at" => "2019-12-01 00:00:00"

]

1 => array:3 [

"name" => "savan"

"email" => "[email protected]"

"created_at" => "2019-12-09 00:00:00"

]

2 => array:3 [

"name" => "piyush"

"email" => "[email protected]"

"created_at" => "2019-12-25 00:00:00"

]

3 => array:3 [

"name" => "keval"

"email" => "[email protected]"

"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);

}

It will help you...