This short post explains how to sort a Drupal collection by date. We’ll put into practice a how to sort date collection in Laravel in this tutorial. Let’s talk about the date-based Laravel collection order. I gave a brief explanation of how to sort a Laravel collection by date desc. See the following tutorial step for an example of sorting a collection by date in Drupal.
To sort the Laravel collection by date, we will utilize the sortBy() method. I’ll give you two easy examples with output so you can have a better understanding. Now, let’s look at some basic 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' => '2023-11-06'],
['id' => 2, 'name' => 'roshan', 'created_at' => '2023-11-10'],
['id' => 3, 'name' => 'Rakesh', 'created_at' => '2023-11-05'],
['id' => 4, 'name' => 'abhishek', 'created_at' => '2023-11-04'],
]);
$sorted = $collection->sortBy('created_at');
$sorted = $sorted->all();
dd($sorted);
}
}
OutPut:
Array
(
[3] => Array
(
[id] => 4
[name] => abhishek
[created_at] => 2023-11-04
)
[2] => Array
(
[id] => 3
[name] => Rakesh
[created_at] => 2023-11-05
)
[0] => Array
(
[id] => 1
[name] => avinash
[created_at] => 2023-11-06
)
[1] => Array
(
[id] => 2
[name] => roshan
[created_at] => 2023-11-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(['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
)