Laravel - Update only blank/empty fields in models
In Laravel, you have the
updateOrCreate method, I was developing an application and I needed to update only the blank fields, but the logic was the same as the update or create method, if the record doesn’t exist, the code needs to create it.
Then I thought, “What if I need the same methods in different models?”, the solution was so close, then I figured out the quickest for me: create a
So, this trait takes the same params as
updateOrCreate method, the filter attributes, and the filling values. I will show you the code, so you can replicate this feature in your own project.
With this, you just need to include the trait into your Laravel Model:
use SecureUpdatable;. Also, you have code completion for your IDE.
How it works?
As you see tries to find the existing model or create a new instance with the static
firstOrNew function. Then filter only the empty values with the blank helper from Laravel.