Laravel or PHP unique with multiple conditions

Question

I'm trying to get the unique rows from a MySQL DB from PHP and Laravel.

In my DB I have:

Email    Errors   Status  
a@a.a    error1   pending
a@a.a    error2   pending
b@b.b    error1   pending
b@b.b    error1   pending

In my head the solution would be:

$transactions->unique('email', 'errors', 'status' )

But that's returning this:

Email    Errors   Status  
a@a.a    error1   pending
b@b.b    error1   pending

And if I try:

$transactions->unique(['email', 'errors', 'status'] )

It's even worse:

Email    Errors   Status  
a@a.a    error1   pending

My perfect solution would be this, so I can see the different errors from each user:

Email    Errors   Status  
a@a.a    error1   pending
a@a.a    error2   pending
b@b.b    error1   pending

That means unique based on several columns.

I was searching everywhere without success, I hope somebody can help :)


Show source
| laravel   | php   | mysql   2017-10-04 22:10 1 Answers

Answers to Laravel or PHP unique with multiple conditions ( 1 )

  1. 2017-10-04 22:10

    You can...

    1) either provide your own function as unique predicate:

    $transactions->unique(function ($item) {
        return $item['email'].'/'.$item['errors'].'/'.$item['status'];
    });
    

    ... assuming that / symbol is never used in either field.

    2) or make such a grouping on query level, using groupBy method:

    $DB::table('transactions')->select('email', 'errors', 'status')
    ->groupBy('email')
    ->groupBy('errors')
    ->groupBy('status')
    ->get();
    

    I'd rather go with the latter.

Leave a reply to - Laravel or PHP unique with multiple conditions

◀ Go back