In my FormRequest I need to validate, if selected category is actually present in the categories array.
I solved my problem with withValidator method, where I manually check if the category is present.
However, I feel like there must be a nicer way of doing this. I went over validation documentation, but could not find my fit.
Has anyone tackled this problem, or do you have an idea how to do this better?
Thank you.
class StoreWarehouseItemRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required',
'category' => 'required|integer',
'specification' => 'nullable|string',
'recipient' => 'nullable|string',
'unit' => 'nullable|string',
'sellers_code' => 'nullable|string',
'note' => 'nullable|string',
];
}
public function withValidator(Validator $validator)
{
$cat = $validator->getData()['category'];
$cats = WarehouseItem::CATEGORIES;
$validator->after(
function ($validator) use ($cat, $cats) {
if (!isset($cats[$cat])) {
$validator->errors()->add('category', 'Kategória musí byť vybraná zo zoznamu.');
}
}
);
}
}
CodePudding user response:
You could use Laravel's in:foo,bar validator.
return [
'name' => 'required',
'category' => ['required', 'integer', Rule::in(WarehouseItem::CATEGORIES)],
'specification' => 'nullable|string',
'recipient' => 'nullable|string',
'unit' => 'nullable|string',
'sellers_code' => 'nullable|string',
'note' => 'nullable|string',
];
Additionally, if you are looking if the key exists in the WarehouseItem::CATEGORIES array, you can do array_flip(WarehouseItem::CATEGORIES) on it.
