Dec 22, 2025
0
Level 1
How to enforce immediate type safety on a ValueObject-casted model property?
Hello,
I have a model DepositMethod, and one of its property is called cost_settings
I casted it like this:
'cost_settings' => AsCollection::of(CostSettingData::Class)
but as far as I know, this casting only mutates the data when accessed. Is there a way to also enforce error if any value formats other than CostSettingData is provided?
Because when I push data like $depositMethod->cost_settings->push(['random' => 'value']), this still works, and I don't want that. One way of course is to validate the request, but I still prefer if it throws an error immediately. Because I want to avoid any format being inserted wrongfully by other devs for some reason.
Please or to participate in this conversation.