Wachaga Mwaura
Wachaga Mwaura

Reputation: 3600

Count duplicate columns in Laravel

How do you count the DUPLICATE columns in a database table using eloquent model querying?

For example, in SQL, there's this command:

SELECT name, COUNT(email) 
FROM users
GROUP BY email 
HAVING ( COUNT(email) > 1 )

The code above will return the names from all columns with similar email addresses.

What I'm trying to achieve is to get the COUNT of duplicate entries, i.e.

$noOfjobsFromSameCustomers = App\Workflow::count();

But I need an additional parameter to specify that the cust_id (a column in the workflows table) is duplicated, something like:

$noOfjobsFromSameCustomers = App\Workflow::notDistinct()->orderBy('cust_id')->count();

For example, given the table below:

 ID  NAME EMAIL 
 1   John [email protected] 
 2   Sam  [email protected] 
 3   Tom  [email protected] 
 4   Bob  [email protected] 
 5   Tom  [email protected] 

How can I count the number of times a specified email address (e.g. [email protected]) recurs?

Upvotes: 1

Views: 4952

Answers (2)

Hiren Makwana
Hiren Makwana

Reputation: 2156

You can use havingRow :

->havingRaw('COUNT(<columneName>) > 1')

Upvotes: 2

D Coder
D Coder

Reputation: 572

you can get this by raw query

$result = DB::select( DB::raw(" select * from (
  SELECT name, COUNT(email) as e_count
  FROM users
  GROUP BY email 
  )a where  a.e_count > 1 ");

and put your where condition in this query Please see for more Larave website

Upvotes: 2

Related Questions