How to Order By in Laravel

To order a query in descending or ascending order in Laravel use the orderBy() method followed by the get() method. The first argument in orderBy() is the column name and the second specifies the order.


Get Posts in Descending Order

Let's get all the items from a Post model in descending order from newest to oldest using the created_at column.


Post::orderBy('created_at', 'desc')->get();


Get Posts in Ascending Order

To perform the same query as above but in ascending order we would do this:


Post::orderBy('created_at', 'asc')->get();


Limit the Number of Posts

To limit the number of items to get, use the take() method, supplying an integer value as the limit. It works with orderBy() like this:


Post::where('status', 1)->orderBy('created_at', 'desc')->take('10')->get();