Laravel Collection Sort By Date Example

By Hardik Savani November 6, 2023 Category : Laravel

Hey Developer,

This simple article demonstrates of laravel collection sort by date. In this article, we will implement a how to sort date collection in laravel. let’s discuss about laravel collection order by date. I explained simply about laravel collection sort by date desc. Follow the below tutorial step of laravel collection sort by date example.

we will use sortBy() method to sort by date in laravel collection. i will give you simple two examples with output that way you can understand better. so, let's see the simple examples:

Example 1:

you can see the below controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$collection = collect([

['id' => 1, 'name' => 'Hardik', 'created_at' => '2023-11-06'],

['id' => 2, 'name' => 'Paresh', 'created_at' => '2023-11-10'],

['id' => 3, 'name' => 'Rakesh', 'created_at' => '2023-11-05'],

['id' => 4, 'name' => 'Mahesh', 'created_at' => '2023-11-04'],

]);

$sorted = $collection->sortBy('created_at');

$sorted = $sorted->all();

dd($sorted);

}

}

Output:

Array

Array

(

[3] => Array

(

[id] => 4

[name] => Mahesh

[created_at] => 2023-11-04

)

[2] => Array

(

[id] => 3

[name] => Rakesh

[created_at] => 2023-11-05

)

[0] => Array

(

[id] => 1

[name] => Hardik

[created_at] => 2023-11-06

)

[1] => Array

(

[id] => 2

[name] => Paresh

[created_at] => 2023-11-10

)

)

Example 2:

you can see the below controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$collection = collect(['2023-11-06', '2023-11-10', '2023-11-05', '2023-11-04']);

$sorted = $collection->sortBy(function ($date) {

return \Carbon\Carbon::createFromFormat('Y-m-d', $date);

});

$sorted = $sorted->all();

dd($sorted);

}

}

Output:

Array

(

[3] => 2023-11-04

[2] => 2023-11-05

[0] => 2023-11-06

[1] => 2023-11-10

)

I hope it can help you...

Shares