erezt
erezt

Reputation: 411

How to check if collection's column matches an array

How do I check if my collection CustomerDocuments contains $neededDocs in each item of this collection.

if all $neededDocsare present in each CustomerDocuments.doc_id then return true, else, false.

I would like to preform this with collection->contains as follows:

CustomersDocuments::where('customer_id', $customer->id)
    ->contains('doc_id',$required_onboarding_docs)
    ->get();

Yet this syntax is wrong

Upvotes: 3

Views: 307

Answers (1)

Mozammil
Mozammil

Reputation: 8750

I think you could probably achieve this with something like the following:

$documents = CustomersDocuments::where('customer_id', $customer->id)
    ->get()
    ->pluck('doc_id')
    ->toArray();

The above will output an array with all the doc_id.

return $documents == $neededDocs; 

You could then just compare it with your $neededDocs array.

Edit: If you, however, want to check that each row in your collection contains a doc_id that is present in $neededDocs, you could do it like this:

$collection = CustomersDocuments::where('customer_id', $customer->id)->get(); 

return $collection->contains(function($value, $key) use ($neededDocs) {
    return in_array($value->doc_id, $neededDocs); 
}); 

I am not entirely sure which one you want, but these should do the trick.

Upvotes: 1

Related Questions