Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Object already exists in Collection - Laravel

Tags:

php

laravel

I am looking to add objects to a new collection as I loop through a series of different results.

The query:

$osRed = Item::where('category', 'Hardware')         ->where(function ($query) {             $query->where('operating_system', 'xxx')                 ->orWhere('operating_system', 'xxx')                 ->orWhere('operating_system', 'xxx');         })         ->orderBy('operating_system', 'ASC')         ->get(); 

Then, loop through these results and add related objects to a new collection.

foreach ($osRed as $os) {         foreach ($os->services as $service) {             if (!($servicesImpacted->contains($service))) {                 $servicesImpacted->push($service);             }         } } 

I then go on to another set of results and add the related services from those results to the collection.

However, it is not picking up that the object is already in the collection and I end up with a large number of (what appear to be) duplicates.

Ideally, I would like to match up on the name attribute of the $service object, but that doesn't seem to be supported by the contains method.

toString() must not throw an exception 
like image 444
kerrin Avatar asked May 27 '17 10:05

kerrin


People also ask

How do you check if data exists in a table SQL in laravel?

$result = User::where("email", $email)->exists(); The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error. Show activity on this post.


2 Answers

You can use contains() with key and value defined:

if (!$servicesImpacted->contains('name', $service->name)) 

Or you could use where() and count() collection methods in this case, for example:

if ($servicesImpacted->where('name', $service->name)->count() === 0) 
like image 76
Alexey Mezenin Avatar answered Sep 23 '22 02:09

Alexey Mezenin


You can use the contains() method in Laravel for Check some specific key of value exists or not. If value available in the collection for the specific key then returns true.

if($collection->contains('product_id',1234)) {   echo "product id 1234 available in collection"; } 
like image 28
Chirag Prajapati Avatar answered Sep 22 '22 02:09

Chirag Prajapati