Skip to main content

Transform Data Before Saving: Mutator or Observer

Lesson 03/30 5:18
Autoplay

Comments & Discussion

C
crThiago ✓ Link copied!

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

PK
Povilas Korop ✓ Link copied!

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!

L
LBannenberg ✓ Link copied!

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.

IU
Inaam ul haq ✓ Link copied!

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.

R|
Rio | ZeroXMK | 鬼神 ✓ Link copied!

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?

PK
Povilas Korop ✓ Link copied!

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

AR
Alonso Ramírez Páez ✓ Link copied!

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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.