In a Laravel model, I am using a JSON column data
to store custom data. The JSON data can be nested for organization, and all keys should have non-empty/non-null values.
At the moment all keys are hard-coded in the form as data[key]
on the frontend. If a key
previously stored has its value
blanked out on the frontend, key
should be unset in the update method. However, upon validation, I'm getting the original array back.
// ModelController.php
public function update(Request $request, Model $model)
{
// $request->data = ['key' => null, 'nested' => ['key' => null]]
function stripEmptyCustom($data) {
foreach ($data as $key => $value) {
if (is_array($data[$key])){
$data[$key] = stripEmptyCustom($data[$key]);
}
if (empty($value)){
unset($data[$key]);
}
}
return $data;
}
$request->data = stripEmptyCustom($request->data);
dump($request->data); // so far, so good
// $request->data = []
$attributes = $request->validate([
'name' => 'nullable',
'data' => 'array',
]);
dump($attributes); // $attributes['data'] =
// ['key' => null, 'nested' => ['key' => null]]
How do I validate the request without it resetting the original data?