I am having problem with available
key in the map
collection.
The available
key use contains
method. It should return true if the value of product id in $unavailableProducts does not contain in $products ($value->product_id == $product->id)
What did I do wrong?
$unavailableProducts = $this->unavailableProducts();
$products = $this->products->all();
$allProducts = $products->map(function ($product) use($unavailableProducts) {
return [
'id' => $product->id,
'title' => $product->title,
'available' => $unavailableProducts['result']->contains(function ($value, $key) use ($product) {
if ($value->product_id == $product->id) {
return false;
}
return true;
}),
];
});
The map method applies a given callback function to each element of a collection. The callback function will modify the item and create a new Laravel collection for them. The map method will not modify the original collection, instead it will return a new collection with all the changes.
This method applies to both Laravel Collection as well as Eloquent Collection object. contains () method checks whether Laravel Collections contains certain given value or not. If you pass one value to the contains () method, it will check whether collection has any value matching to the parameter.
Note: The map () method will not modify the original Laravel Collection, so it is safe to use without worrying about unknown data mutation. The Callback function requires two parameters - $item, $key in this order.
The callback function will modify the item and create a new Laravel collection for them. The map method will not modify the original collection, instead it will return a new collection with all the changes. The provied callback function should accept the $item and the items $key as it’s only argument.
First, make sure that $unavailableProductions['result']
is a collection.
Second, change your contains
method like this:
$unavailableProducts = $this->unavailableProducts();
$products = $this->products->all();
$allProducts = $products->map(function ($product) use($unavailableProducts) {
return [
'id' => $product->id,
'title' => $product->title,
'available' => $unavailableProducts['result']->contains('id', $product->id),
];
});
The $unavailableProducts['result']->contains('id', $product->id)
will determine if the $unaviableProductions['result']
collection has a key id
where the value is $product->id
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