Laravel 8 orderBy()
, groupBy()
, and limit()
Query Examples
In this tutorial, we will explore how to use Laravel's query builder methods orderBy()
, groupBy()
, and limit()
to efficiently retrieve and organize data from your database.
orderBy()
– Sorting Query Results
The orderBy()
method allows you to sort the query results by a specific column.
Example:
SQL Equivalent:
Output:
This will return all users sorted by their name
in descending order.
groupBy()
– Grouping Results
The groupBy()
method groups query results by a given column, often used with aggregate functions or having()
clauses.
Example:
SQL Equivalent:
Output:
Returns grouped records with account_id
greater than 100.
limit()
– Limiting Results
The limit()
method limits the number of records returned from the query.
Example:
SQL Equivalent:
Output:
Returns only the first 5 users from the users table.
Summary
Method | Purpose |
---|---|
orderBy | Sort records by a column |
groupBy | Group records by a common field |
limit | Restrict the number of returned rows |
These methods can be combined to build powerful queries and retrieve only the necessary data efficiently.