Laravel Distinct

Laravel provides a “distinct” method to retrieve only unique records from a database table. This method can be used in conjunction with the “select” method to specify the columns you want to retrieve the distinct records from.

Here’s an example of how you can use the “distinct” method in Laravel:

    
      $uniqueRecords = DB::table('users')
                      ->select('name')
                      ->distinct()
                      ->get();
    
  

In this example, we are retrieving distinct names from the “users” table. The “distinct” method ensures that duplicate names are not included in the result set.

You can also use the “distinct” method with multiple columns. For example:

    
      $uniqueRecords = DB::table('users')
                      ->select('name', 'email')
                      ->distinct()
                      ->get();
    
  

This would retrieve distinct combinations of names and emails from the “users” table.

Similar post

Leave a comment