In Laravel, the distinct()
method is a powerful query builder method that allows you to retrieve distinct or unique records from a database table. This method eliminates duplicate rows from the result set, providing you with a clean and filtered dataset. In this post, we'll dive into the distinct()
method in Laravel and provide you with examples to illustrate its usage. Let's get started!
What is the distinct()
Method? The distinct()
method is used in Laravel to retrieve unique records from a database table based on specific columns. It ensures that each record returned in the result set is distinct, eliminating any duplicate entries. By applying this method, you can efficiently filter your data and avoid redundancy.
Syntax The basic syntax of the distinct()
method in Laravel is as follows:
DB::table('table_name')->distinct()->get();
Example Usage Let's explore a few examples to understand how the distinct()
method works in Laravel:
Example 1: Retrieving Distinct Values from a Single Column Suppose you have a users
table with a column named country
. You want to retrieve the distinct values from the country
column. Here's how you can achieve that using the distinct()
method:
$uniqueCountries = DB::table('users')->distinct()->pluck('country');
In the above example, the distinct()
method is applied to the users
table, and the pluck()
method is used to retrieve only the distinct values from the country
column. The $uniqueCountries
variable will contain an array of unique country names.
Example 2: Retrieving Distinct Values from Multiple Columns If you need to retrieve distinct values based on multiple columns, you can pass an array of column names to the distinct()
method. For instance, let's say you have a products
table with columns name
and category
, and you want to fetch the unique combinations of product names and categories. Here's how you can achieve that:
$uniqueProducts = DB::table('products')->distinct(['name', 'category'])->get();
In this example, the distinct()
method is called with an array of column names (name
and category
), and the get()
method retrieves all distinct combinations of product names and categories from the products
table.
Experiment with the distinct()
method in your Laravel applications and explore its versatility in handling various scenarios.
Thank you!