How To Sort Items by Date In Laravel Collection Tutorial

Reading Time: 3 minutes
455 Views

When you wish to organise your data by date or any other criteria, sorting objects in a Laravel Collection is a typical process. This tutorial will walk you through the process of sorting objects in a Laravel Collection by date. This lesson is intended for all skill levels, whether you are a novice or an experienced Laravel developer.

Date-based sorting is essential for a wide range of applications, including event calendars, news archives, and task management systems. It lets you present facts in a logical and chronological arrangement, which improves the user experience.

We will use sortBy() method to sort by date in laravel collection.

Read More: How To Remove Item by Value From Laravel Collection

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Example #1: Sort Items by Date In Laravel Collection

Here, is an example. Please check it,

Code

Output

Array
(
    [3] => Array
        (
            [id] => 4
            [name] => Dinesh
            [created_at] => 2023-11-04
        )
    [2] => Array
        (
            [id] => 3
            [name] => Vijay
            [created_at] => 2023-11-05
        )
    [0] => Array
        (
            [id] => 1
            [name] => Sanjay
            [created_at] => 2023-11-06
        )
    [1] => Array
        (
            [id] => 2
            [name] => Ashish
            [created_at] => 2023-11-10
        )
)

Example #2: Sort Items by Date In Laravel Collection

Here, is another example. Please check it,

Code

Output

Array
(
    [3] => 2023-11-04
    [2] => 2023-11-05
    [0] => 2023-11-06
    [1] => 2023-11-10
)

That’s it.

We hope this article helped you to learn about How To Sort Items by Date In Laravel Collection Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.