BelongsToMany relation. How to get unique rows
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();
}
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');
}