Laravel orderBy, groupBy and limit Example

Laravel orderBy, groupBy and limit Example

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:

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

SQL Equivalent:

SELECT * FROM `users` ORDER BY `name` DESC;

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:

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

SQL Equivalent:

SELECT * FROM `users` GROUP BY `account_id` HAVING `account_id` > 100;

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:

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

SQL Equivalent:

SELECT * FROM `users` LIMIT 5;

Output:

Returns only the first 5 users from the users table.

Summary

MethodPurpose
orderBySort records by a column
groupByGroup records by a common field
limitRestrict the number of returned rows

These methods can be combined to build powerful queries and retrieve only the necessary data efficiently.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close