Search code examples
phparrayslaravellaravel-5collections

how create a collection of models from array with their IDs - Laravel


I am creating a foreach loop with button attach (name)' for each model which is not connected to the base model with abelongsToMany` 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

My question: how to get a collection out of the $missing_stages array

The array is created as expected

My question (alternative solution)

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.


Solution

  • You can use whereNotIn() for your problem as:

    $attached_stages = $object->stages()->getRelatedIds()->toArray();
    
    $missing_stages = Stage::whereNotIn('id', $attached_stages)->get();