Courses

Eloquent: The Expert Level (Laravel 9)

WasCreated, IsDirty and Other Checks If Model Was Changed

Previous: FirstOrCreate, and Other 2-in-1 Methods
avatar

How does the "wasChanged" works under the hood? The model should be edited and saved to DB through Laravel, for this functionality to work or data in DB can be chaged from outside and this method will still know about the change?

How long this "Changed" status is present. I mean if model changed in the morning, and we'll check it in the evening - will it tell us 'true'? Or it's just instant - for the current code run?

It's kind of interesting functionality, however what might be real-world usage for it? Just wonder who needs it?

avatar

This is only for ONE request. It's a rare case indeed, mostly if many pieces of code may change the model and in your piece of code you want to find out whether someone else changed the model or not.

avatar
You can use Markdown
avatar

Hello.

Could you do a real example with forms, StoreRequests, etc. and put them in real life? Like "FirstOrCreate", "FirstOrNew" and "updateOrCreate"?

thnx

avatar

I think I've done it multiple times on YouTube, just search for "firstOrCreate" or "updateOrCreate" on my channel. "FirstOrNew" I don't remember using myself.

Found one: /video/eloquent-upsert-vs-updateorcreate-practical-demo

avatar
You can use Markdown
avatar

hello, can we check wasCreated function on UpdateorCreated function also?

avatar

Good question. I don't remember trying, but you should try and see.

avatar
You can use Markdown
avatar
You can use Markdown