Photo by Ben Griffiths on Unsplash

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 Trait
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.
1
<?php
2
3
namespace App\Traits;
4
5
trait SecureUpdatable
6
{
7
/** @method static $this updateBlankOrCreate($hashedId, array $columns = []) */
8
9
/**
10
* @param $attributes
11
* @param $values
12
* @return \Illuminate\Database\Eloquent\Model|$this
13
*/
14
public static function updateBlankOrCreate($attributes, $values)
15
{
16
/** @var \Illuminate\Database\Eloquent\Model $model */
17
$model = static::firstOrNew($attributes);
18
19
$blankValues = collect($values)->filter(function ($fieldValue, $fieldName) use ($model) {
20
/** @var \Illuminate\Database\Eloquent\Model $model */
21
return blank($model->getAttribute($fieldName));
22
})->toArray();
23
24
$model->fill($blankValues)->save();
25
26
return $model;
27
}
28
}
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.
My posts are not AI generated, they might be only AI corrected. The first draft is always my creation

Author

Written by Helmer Davila