I am creating a foreach loop with button attach (name)' for each model which is not connected to the base model with a
belongsToMany` relation.
I have an array with IDs for a certain model
$attached_stages = $object->stages()->getRelatedIds()->toArray(); // output: 1, 2
Then I have all model instances for the same model,
$all_stages = Stage::orderBy('id', 'asc')->pluck('id')->all(); // output: 1,2,3,4 ... 6
$missing_stages = array_diff($all_stages, $attached_stages); // output: 3,4,5,6
$missing_stages
arrayThe array is created as expected
What I am actually trying to get here is a collection of models which are not attached to the main $object
with the stages()
relation.
The relation is defined as follows:
public function stages()
{
return $this->belongsToMany('App\Models\Stage', 'lead_stage', 'lead_id', 'stage_id')->withPivot('id','status')->withTimestamps();
}
and I am unable to get my desired collection with this code:
$all_stages = Stage::get(); // output: collction 1,2,.... 6
$attached_stages = $object->stages(); // output: 1, 2
$missing_stages = $all_stages->diff($attached_stages); // expected output: 3,4,5,6
Note: I attempted to remove the pivot part in relation definition, but it didn't help, the diff
method is not working for me. Nothing is cut from the collection.
Any help appreciated. Thx.
You can use whereNotIn()
for your problem as:
$attached_stages = $object->stages()->getRelatedIds()->toArray();
$missing_stages = Stage::whereNotIn('id', $attached_stages)->get();