Shouldn't model validation occur after beforeCreate?

Hello,

Bring up a scenario that I came across which would be the following.

I have some default values ​​to define if they are null and I am defining this in the model’s beforeCreate event, however the validation trait checks before going through this event, preventing, for example, me from defining a default value in a field that is defined in the validation rules.

Hey @kallef

Validation occurs before creation, so this method should be beforeValidate. It is designed this way since validation usually deals with user input and can be bypassed by the system processes.

I know this method, I just didn’t think it was the ideal method for defining default values ​​before creation.

beforeValidate is a reliable method for this. It will always run, even if validation is skipped. When it is skipped, the validation runs against an empty ruleset, so the event still fires. The only time it doesn’t fire is when the trait is not used on the model class.

When applying defaults, you may also find the need to adjust the validation rules. This is another reason to reach for this method.

1 Like