Laravel collection using map and contains
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" } ] }]