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?
$this->input()this is a method that returns a value. So each time you call it then will this be a new value or does it set the value back to wherever it gets the data from?if, something like$options = $this->input('options')['additional_product_options'];and then process$optionsinstead.