Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BelongsToMany relation. How to get unique rows

I have next 'member_companies' table in DB:

enter image description here

And in model Member has a relation :

public function companies()
{
    return $this->belongsToMany(Company::class, 'member_companies');
}

And it return me all companies with dublicates. For example, Member::find(238)->companies->pluck('id') return

[
  6,
  5,
  7,
  2,
  10,
  8,
  4,
  13,
  14,
  10,
  8,
  13
]

But I want only unique items. Like

[
    6,
    5,
    7,
    2,
    10,
    8,
    4,
    13,
    14,
]   

How can I do it with eloquent relations?

like image 514
Igor Ostapiuk Avatar asked Apr 11 '19 13:04

Igor Ostapiuk


2 Answers

Not sure if its a new addition, but you can do this (at least in Laravel 7):

public function companies()
{
    return $this->belongsToMany(Company::class, 'member_companies')->distinct();
}
like image 138
Arun Batar Avatar answered Sep 24 '22 03:09

Arun Batar


You should use the unique() method in your controller:

Member::find(238)->companies->pluck('id')->unique('id');

Docs:

The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys

When dealing with nested arrays or objects, you may specify the key used to determine uniqueness

Or in your relation you could use groupBy():

public function companies()
{
    return $this->belongsToMany(Company::class, 'member_companies')->groupBy('id');
}
like image 45
Piazzi Avatar answered Sep 21 '22 03:09

Piazzi