Laravel How to Order by Multiple Columns

Hello Artisans, today I'll show you how to order our datasets by multiple columns. Often, we feel some hesitation, how to order by using multiple columns. I'll give you two examples for that. Let's see the examples.

Example 1

In the first example, we'll use eloquent to get our expected result.

public function index()
{
    $users = User::orderBy('created_at', 'desc')->orderBy('status','desc')->paginate(10);

    dd($users);
}

Here what we do is, first we'll order our result by newly created user and after that we'll order that collection by status column.

Now let's see the below example

Example 2

public function index()
{
    $users = User::orderByRaw("created_at desc, status desc")->paginate(10);

    dd($users);
}

In the above example we'll get the same result what we get in the example 1.

That's it for today. Hope you've enjoyed this tutorial. Catch me in the comment section if anything goes wrong. Thanks for reading.