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.
Hm, no the published attribute exists, I accidently removed it from the displayed array above cause there’re several other attributes. Sorry for this.
But I found the issue:
While using the code above with the list switch button, the following rule worked: 'category_id' => ' required_if:published,true',
However, when I tried the validation with the regular save button while editing the model, the variant with “true” didnt work while this one did: 'category_id' => ' required_if:published,1',
This feels strange… one time the true works, one time a “1”.
This here is the DB field if needed: $table->boolean('published')->default(0)
I had another look into this and what should I say: If you go on googling this problem, you find it over and over since Laravel 5. So a fix will most likely not come from OctoberCMS.
Your suggestion of using the $casts property in the model didnt work out well protected $casts = ['published' => 'integer'];
Neither boolean nor integer didnt change anything about the problem.
What did help now were a simple build of two rules testing for the integer and the boolean value: 'category_id' => ['required_if:published,1', 'required_if:published,true'],
It’s not pretty and the natively generated validation messages are difference since one ends on “…1”, the other on “…true”, but this can be changed.
That’s at least my solution after all the research…