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; }), ]; }); 
1

2 Answers

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

You can try this approach

 $policyPackageDetails = PolicyPackage::where('isactive', '=', 1)->where('id', '=', $pid) ->with('policy_package_details') ->select('id', 'title', 'subtitle', 'shorttitle', ) ->get(); $policyPackageDetails = $policyPackageDetails ->map(function ($item){ return collect([ 'id' => $item->id, 'title' => $item->title, 'subtitle' => $item->subtitle, 'short_title' => $item->shorttitle, 'policy_package_details' => $item->policy_package_details->map(function ($details){ return [ 'attribute_name' => $details->attname, 'attribute_value' => $details->attvalue, ]; }), ]); }); 

here fetching data from relational models, remaining & filtering them, the output will be like

[ { "id": 61, "title": " Health (Platinum)", "subtitle": "for 1 year", "short_title": "HL-SHP-1", "policy_package_details": [ { "attribute_name": "in", "attribute_value": "180000" }, { "attribute_name": "out", "attribute_value": "20000" } ] } ] 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy