Example of Laravel Collection Sort By Date

Posted by

How to sort a Drupal collection by date is covered in this brief article. In this lesson, we’ll practice sorting a date collection in Laravel. Let’s discuss the Laravel collection order that is dependent on dates. I briefly described the process of sorting a Laravel collection by date desc. To see an example of sorting a collection in Drupal by date, refer to the ensuing tutorial step.

We’ll use the sortBy() method to order the Laravel collection by date. I’ll walk you through two simple examples with output to help you grasp. Let’s now examine a few simple examples:

Example 1:

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' => 'avinash', 'created_at' => '2024-01-06'],
            ['id' => 2, 'name' => 'Dharmendra', 'created_at' => '2024-01-10'],
            ['id' => 3, 'name' => 'Rakesh', 'created_at' => '2024-01-05'],
            ['id' => 4, 'name' => 'abhishek', 'created_at' => '2024-01-04'],
        ]);
  
        $sorted = $collection->sortBy('created_at');
  
        $sorted = $sorted->all();
      
        dd($sorted);
    }
}

OutPut:

Array
(
    [3] => Array
        (
            [id] => 4
            [name] => abhishek
            [created_at] => 2024-01-04

        )

    [2] => Array

        (
            [id] => 3
            [name] => Rakesh
            [created_at] => 2024-01-05
        )

    [0] => Array

        (
            [id] => 1
            [name] => avinash
            [created_at] => 2024-01-06
        )

    [1] => Array

        (
            [id] => 2
            [name] => Dharmendra
            [created_at] => 2024-01-10
        )
)

Example 2:

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(['2024-01-06', '2024-01-10', '2024-01-05', '2024-01-04']);
    
        $sorted = $collection->sortBy(function ($date) {
            return \Carbon\Carbon::createFromFormat('Y-m-d', $date);
        });
      
        $sorted = $sorted->all();
      
        dd($sorted);
    }
}

OutPut:

Array(  
  [3] => 2024-01-04  
  [2] => 2024-01-05   
  [0] => 2024-01-06  
  [1] => 2024-01-10
  )
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x