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
$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.
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)
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"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With