Courses

How to Structure Laravel Projects

avatar

Hi, what you think about prepareForValidation method to transform data?

avatar

Yes, it exists, but personally it didn't stick with me, too "hidden" place to transform data. But if it works well for you, good!

avatar

I dunno if it's all that hidden. It's documented; https://laravel.com/docs/10.x/validation#preparing-input-for-validation

Suppose you have a frontend where you have some localization with date formats going on, while inside your backend everything is standardized. Then the prepareForValidation seems like a good "first line of defense" for making the incoming data fit your standard format.

On the other hand, if you have dates coming from a lot of different directions in different formats, then I think putting the logic in the model as a "last line of defense" makes more sense. Maybe with some check to sniff what kind of format a given date is in.