I have two functions in controller, "store()" for inserting single item in database, and "bulkInsert()" for storing multiple items.
I can't figure out why my validation rule for checking uniqueness for multiple values doesn't work when I'm validating data in nested array (array of key,value pairs in request), but works OK when data is not nested (simple key,value pairs in request).
Here is my validation code for single insert action:
$input = Validator::make($request->all(), [
'group_id' => ['required', 'numeric'],
'tag' => ['required', 'string', 'max:255'],
'subgroup' => [
'required', 'string', 'max:255', Rule::unique('ram_templates', 'subgroup')
->where('group_id', $request->group_id)
->where('tag', $request->tag)
],
], [
'group_id.required' => __('Group must be selected'),
'subgroup.required' => __('Subgroup must be selected'),
'subgroup.unique' => __('Combination of values for group, subgroup and tag not unique.'),
])->validate();
If I try to submit duplicate data, in frontend I receive '422 status' and correct message from validator.
Here is the validation code for multiple insert action:
$input = Validator::make($request->fields, [
'*.create' => ['boolean'],
'*.group_id' => ['required_if:*.create,true'],
'*.subgroup' => [
'required_if:*.create,true',
Rule::unique('ram_templates', 'subgroup')
->where('group_id', $request->group_id)
->where('tag', $request->tag)
],
'*.tag' => ['required', 'string'],
], [
'*.group_id.required_if' => __('Group must be selected.'),
'*.subgroup.required_if' => __('Subgroup must be selected.'),
'*.subgroup.unique' =>
__('Combination of values for group, subgroup and tag not unique.'),
])->validate();
If duplicate data is submitted, I get '500 status' in frontend, and in Laravel's log I can see the SQL error about
duplicate key value insertion attempt. I would like to add that all other rules for nested array validation are working OK.
Do I need to loop through array like mentioned in documentation or something else needs to be done?
Thanks in advance!