I have figured out all of the issues I had with this on my own up until here. So far I got this to work to the point where I am able to save data properly. The only question I have is, how do I remove arrays where addon_id is not present?
I want to remove the last two "addon_price" from an array.
[
{"addon_id":"7","addon_price":"12"},
{"addon_id":"8","addon_price":"45"},
{"addon_id":"9","addon_price":"66"},
{"addon_price":null}, <- remove
{"addon_price":null} <- remove
]
This is my code
$p = ItemsAddon::where('item_id', $request->item_id)->pluck('addon_id');
if($request->addon_id) {
$addons = [
'addon_id' => $request->addon_id,
'addon_price' => $request->addon_price
];
$values = [];
foreach($addons as $key => $addon) {
foreach($addon as $subkey => $subvalue) {
$values[$subkey][$key] = $subvalue;
}
}
foreach($values as $vkey => $value) {
$item_addon = new ItemsAddon;
if(!$p->contains($value['addon_id'])) {
$item_addon->item_id = $request->item_id;
$item_addon->addon_id = $value['addon_id'];
$item_addon->addon_price = $value['addon_price'];
$item_addon->save();
} else {
$item_addon->where(
[
'item_id' => $request->item_id,
'addon_id' => $value['addon_id'],
])->update([
'addon_id' => $value['addon_id'],
'addon_price' => $value['addon_price'],
]);
}
}
}
CodePudding user response:
If you have an array like this
$a = [
["addon_id" => "7", "addon_price" => "12"],
["addon_id" => "8", "addon_price" => "45"],
["addon_id" => "9", "addon_price" => "66"],
["addon_price" => null],
["addon_price" => null]
];
then you can filter null values in this way:
$b = collect($a)->filter(function ($r) {
return isset($r["addon_id"]);
})->toArray();