Courses

How to Structure Laravel 9 Projects

Transform Data Before Saving: Mutator or Observer

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.

avatar

Hello, I have an issue. When I use this with my user model to make first name and last name with single attribute Full name the response is slow. It takes almost 60s for load.

avatar
Rio | ZeroXMK | 鬼神

Is there a mechanism for creating a globally usable mutator? For example, I may want to display calendars and format the dates per a region-specific format, but record all dates in the DB in Y-m-d format. Can we set an application-wide mutator, or must the mutator be set for every model?

avatar

One way would be to use Traits and include that trait in every Model.

avatar
Alonso Ramírez Páez

I don't know if you forget, but if Observer is used, doesn't it need to be registered in EventServiceProvider? 🤔