Search code examples
phplaraveleloquentmodelrelationship

Laravel: Check if Models have same relation


I have models: Partido and Coalicion related in a many to many relationship. I need to know when two or more Coalicion has the same Partido related.

Hope I have explained myself.

Edit 1: Model:

class Coalicion extends Model
{
    public function partidos()
    {
        return $this->belongsToMany(Partido::class);
    }
}

Let's say users selected some elements from a select input and I grabbed them in an array and send them to the controller.

    ...
    public function example(Request $request)
        {
            $coaliciones = $request->coaliciones;
            foreach ($coaliciones as $c) {
                $coalicion = Coalicion::find($c);
                # Here we have a list of Coalicion model in a loop
                # Let's say the first iteration I can see the relationship
                dump($c->partidos);
            }
        }

This for example give me the following answer at the browser:

Collection {#1 ▼
  #items: array:2 [▼
    0 => Partido {#271 ▶} #This is Partido with id 1
    1 => Partido {#268 ▶}
  ]
}
Collection {#2 ▼
  #items: array:3 [▼
    0 => Partido {#279 ▶}
    1 => Partido {#280 ▶}
    2 => Partido {#283 ▶} #This is Partido with id 1
  ]
}

I need to know when the item 0 of the first Collection and the item 2 of the second Collection are the same.


Solution

  • I kinda found a way but I don't know if it's the correct or best approach. In Coalicion model I add the following function:

    public function partidosId()
        {
            return $this->partidos->pluck('id');
        }
    

    With this I can get only the id's from the relations, then in the controller I created an empty array() and fill it with all my ids with a foreach loop, then, finishing up I evaluated if the id's in the now filled array are unique, if the unique values are less than the length of the array then some models have the same relation (I don't know which but It's a start), e.g.:

    public function example(Request $request)
        {
            $coaliciones = $request->coaliciones;
            $allItems = [];
            foreach ($coaliciones as $c) {
                $coalicion = Coalicion::find($c);
                $allItems = array_merge($allItems, $coalicion->partidosId()->toArray());
            }
            if (count(array_unique($allItems))<count($allItems)) {
                dd("Duplicates");
            }else{
                dd("Uniques");
            }
        }
    

    If anyone find a better way or a way to know which are the ones with the duplicate relation please let me know