Search code examples
laravelcounteloquentdistinct

Laravel Eloquent - distinct() and count() not working properly together


So I'm trying to get the number of distinct pids on a query, but the returned value is wrong.

This is what I try to do:

$ad->getcodes()->groupby('pid')->distinct()->count()

what returns the value "2", while the value it should return, should be "1".

As a workaround, I'm doing this:

count($ad->getcodes()->groupby('pid')->distinct()->get())

what works fine and returns "1"

Is there any rule where count and distinct cannot be on the same query? I find the workaround kind of "heavy", I would like to make the original query work :(


Solution

  • The following should work

    $ad->getcodes()->distinct()->count('pid');