Laravel orderBy, groupBy and limit Example

Websolutionstuff | Jan-27-2021 | Categories : Laravel PHP MySQL

In this article, we will see the laravel orderBy, groupBy, and limit examples. Here we will see different types of laravel 6/7/8 query examples. You can use the order by, group by, and limit functions for getting records from the database.

So, let's see the query of orderBy in laravel 7 and laravel 8, the query of the group by in laravel 7/8, and get a limited no of records in laravel 7/8.

The orderBy method allows you to sort the results of the query by a given column. The first argument accepted by the orderBy method should be the column you wish to sort by, while the second argument determines the direction of the sort and may be either asc or desc.

Laravel orderBy() Function

Laravel Example:

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

SQL Query:

select * from `users` order by `name` desc;

Output:

All user's names will be sorted in descending order.

 

Laravel groupBy() Function

The groupBy and having methods may be used to group the query results. The having method's signature is similar to that of the where method.

$users = DB::table('users')
         ->groupBy('account_id')
         ->having('account_id', '>', 100)
         ->get();

 

Laravel limit() Function

The limit method is used to limit the number of results returned from the query.

$users = DB::table('users')
         ->limit(5)
         ->get();

 

Recommended Post
Featured Post
How To Get Children Element In jQuery
How To Get Children Element In...

In this article, we will see how to get the children of this selector in jquery. You can use the find() method...

Read More

Jul-13-2022

Laravel 10 AJAX CRUD Operations Example
Laravel 10 AJAX CRUD Operation...

In this article, we will see the laravel 10 ajax crud operations example. Here, we will learn about ajax crud operation...

Read More

Feb-27-2023

Laravel 8 QR Code Generator Example
Laravel 8 QR Code Generator Ex...

In this tutorial, we will see the laravel 8 QR code generator example. we will generate QR code using simpleso...

Read More

Jan-24-2022

How to Create Apexcharts Line Chart in Laravel 11
How to Create Apexcharts Line...

Hello developers! In this article, we'll see how to create apexcharts line chart in laravel 11. ApexCharts is a...

Read More

Apr-22-2024