almo
almo

Reputation: 6387

Laravel 4 select distinct

I have a table with email addresses and want to make a disctinct select (dont have duplicate email addresses in my result). The column with the email address is called 'mail_address'

I have tried:

ContactMail::distinct('mail_address')->get();

And:

ContactMail::distinct()->get();

But both give me just the complete table, also the rows where I have the same email address.

The complete query that I am building looks like this:

$list = ContactMail::where('campaign_id', '=', $campaign_id)
                ->where('mail_address', '!=', '')
                ->distinct('mail_address')
                ->get();

What am I doing wrong? I did not find good docu for distinct.

Upvotes: 1

Views: 1539

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Using distinct in ORM is a bit pointless - in the end every model is distinct.

So I suggest, that you don't load the models, but single field that you need:

$list = ContactMail::where('campaign_id', '=', $campaign_id)
    ->where('mail_address', '!=', '')
    ->distinct()
    ->lists('email_address');

This way you get an array of distinct emails, instead of full models, or incomplete models when using select and get

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

$list = ContactMail::where('campaign_id', '=', $campaign_id)
            ->where('mail_address', '!=', '')
            ->select('mail_address')
            ->distinct()
            ->get();

Upvotes: 0

Related Questions