Reputation: 3950
I've run into a specific problem, where I need to remove specific nested array key from my request, so it doesn't store in my database. I created a Request class, and this is how I tried to accomplish this so far:
This is my data that I'm getting from request after form submit:
"options" => array:2 [▼
"product_options" => array:1 [▶]
"additional_product_options" => array:1 [▼
"Tenetur dolor labore" => null
]
]
As you can see, additional_product_options
array has a key with an empty value, and so I want to remove this key from array completely. I tried this using both unset()
and array_filter()
, but I'm not getting desired result. This is how I tried it so far:
if(isset($this->input('options')['additional_product_options'])){
foreach ($this->input('options')['additional_product_options'] as $key => $val){
if(is_null($key) || is_null($val)){ //Check for null values
unset($this->input('options')['additional_product_options'][$key]); //Remove key from array
}
}
}
After I dump my request with dd($this->options())
, I'm still getting Tenetur dolor labore
key in this array:
array:2 [▼
"product_options" => array:1 [▼
"Et sit id culpa rep" => "sdad,ads"
]
"additional_product_options" => array:1 [▼
"Tenetur dolor labore" => null
]
]
With array_filter()
, I'm still getting the same results:
if(isset($this->input('options')['additional_product_options'])){
array_filter($this->input('options')['additional_product_options']);
}
After dumping my data, the key is still here:
"options" => array:2 [▼
"product_options" => array:1 [▶]
"additional_product_options" => array:1 [▼
"Tenetur dolor labore" => null
]
]
In ideal case,the Tenetur dolor labore
key would be removed completely, and additional_product_options
array would be empty. What am I doing wrong here?
Upvotes: 1
Views: 729
Reputation: 12188
try this ... i have test it for current options array:
for test reason, i made the option array:
$options = ['product_options' => ['additional_product_options' =>
['Tenetur dolor labore' => null]], 'additional_product_options' => 'some value'];
then
unset($options['product_options']['additional_product_options']['Tenetur dolor labore']);
the result is removing the key as we want ...
Upvotes: 1