I'm using laravel 5.6 and I need to filter my input. laravel has pretty beautiful validation system . I'm wondering is there any way that instead of showing error when inputs are not what we want according to rules, remove those incorrect results. like example below this is my rule
$this->validate($request , [
'room_attributes.*.title' => 'required' ,
'room_attributes.*.value' => 'required' ,
]);
these are the data that I receive from the form
"room_attributes" => array:6 [▼
0 => array:2 [▼
"title" => "title 1"
"value" => "val1"
]
1 => array:2 [▼
"title" => "title2"
"value" => "val2"
]
2 => array:2 [▼
"title" => "title3"
"value" => null
]
3 => array:2 [▼
"title" => null
"value" => "val4"
]
4 => array:2 [▼
"title" => null
"value" => null
]
5 => array:2 [▼
"title" => null
"value" => null
]
]
and with the current rule, I receive these errors
The room_attributes.3.title field is required.
The room_attributes.4.title field is required.
The room_attributes.5.title field is required.
The room_attributes.2.value field is required.
The room_attributes.4.value field is required.
The room_attributes.5.value field is required.
but I want to filter my data so I filter my inputs and receive this array as result (the only ones that have both title and value filled )
0 => array:2 [▼
"title" => "title 1"
"value" => "val1"
]
1 => array:2 [▼
"title" => "title2"
"value" => "val2"
]
dose laravel provide functionality like that? either laravel itself or some third party library?
thanks in advance
You could try something like this:
$data = $request->all();
$data['room_attributes'] = collect($data['room_attributes'])->filter(function($item){
return !is_null($item['title']) && !is_null($item['value']);
})->toArray();
Validator::make($data, [
'room_attributes.*.title' => 'required',
'room_attributes.*.value' => 'required',
])->validate();
More info on the filter collection method: https://laravel.com/docs/5.7/collections#method-filter