I got the following $rules for a certain model:
public $rules = [
'name' => 'required',
'category_id' => 'required_if:published,1',
];
The Category is a relation:
public $belongsTo = [
'category' => [
Category::class,
'order' => 'name'
]
];
Now, if I save the model within the create/edit view and for example the name is missing or I try to publish if no category is set, everything just works fine: The validation error is thrown and nothing is saved.
Now I added a listswitch to my list (basically a bit more advanced version of the listswitch plugin) which should perform this validation, too:
private function processInvertField($modelClass, $id, $fieldName, $dateFieldOnTrue)
{
if (empty($fieldName) || empty($id) || empty($modelClass)) {
throw new ApplicationException("Following parameters are required : id, field, model");
}
$item = $modelClass::findOrFail($id);
# If Item is set to true, also set this datefield to the actual date
if (!empty($dateFieldOnTrue) && !$item->{$fieldName}) {
$item->{$dateFieldOnTrue} = Carbon::now();
}
$item->{$fieldName} = !$item->{$fieldName};
# Validate
# $item->name = '';
$validator = Validator::make($item->attributes, (new $modelClass)->rules);
if ($validator->fails()) {
throw new ApplicationException($validator->getMessageBag()->first());
}
$item->save();
}
I posted the whole method, but just the validation part is relevant. I call the validator and it does not apply for the category_id and I dont know why. If I remove the name with the commented line, the validation message is thrown. Not for the category.
What did I miss?
Thanks for every kind of help