How to Sort Data in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this article we will learn how to sort data in laravel.

 

How to sort data in laravel

To sort data in Laravel, you can use the orderBy method provided by Laravel's Query Builder.

 

Assuming you have a users table in your database and you want to retrieve all users sorted by their name in ascending order, you can use the following code:

$users = DB::table('users')
            ->orderBy('name', 'asc')
            ->get();

In this example, the orderBy method is used to sort the records by the name column in ascending order. The asc parameter is optional, as ascending order is the default order.

 

If you want to sort the records in descending order, you can use the following code:

$users = DB::table('users')
            ->orderBy('name', 'desc')
            ->get();

 

You can also sort records by multiple columns. For example, to sort users by their name in ascending order, and then by their email in descending order, you can use the following code:

$users = DB::table('users')
            ->orderBy('name', 'asc')
            ->orderBy('email', 'desc')
            ->get();

In this example, the orderBy method is called twice to sort the records by the name column in ascending order, and then by the email column in descending order.

 

You can also use the orderBy method with Eloquent models. For example, if you have an User model, you can sort all users by their name in ascending order like this:

$users = User::orderBy('name', 'asc')->get();

This will return a collection of User instances sorted by their name in ascending order.

 

That's it! You can use the orderBy method to sort your data in Laravel.

Comments 0

Leave a comment