📜  laravel order by desc - PHP (1)

📅  最后修改于: 2023-12-03 15:32:33.622000             🧑  作者: Mango

Laravel Order By Desc - PHP

When working with databases, it is often necessary to retrieve data in a specific order. In Laravel, we can do this by using the orderBy() method.

Basic Usage

To sort data in descending order, we can use the orderByDesc() method. Here's an example of how to retrieve a collection of users in descending order by their ID:

$users = DB::table('users')
            ->orderByDesc('id')
            ->get();

In this example, we're using the orderByDesc() method to order the users table by the id column in descending order.

Order By Multiple Columns

We can also order by multiple columns by chaining the orderBy() or orderByDesc() method. For example, to sort users by their name in descending order, then by their ID in ascending order, we can do:

$users = DB::table('users')
            ->orderByDesc('name')
            ->orderBy('id')
            ->get();

In this example, we're using the orderByDesc() method to sort users by their name in descending order, then the orderBy() method to sort them by their ID in ascending order.

Conclusion

The orderByDesc() method in Laravel gives us an easy way to retrieve data in descending order from our database. By chaining it with other methods, we can also sort by multiple columns.