Laravel - Update only blank/empty fields in models

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.

<?php
namespace App\Traits;
trait SecureUpdatable
{
/** @method static $this updateBlankOrCreate($hashedId, array $columns = []) */
/**
* @param $attributes
* @param $values
* @return \Illuminate\Database\Eloquent\Model|$this
*/
public static function updateBlankOrCreate($attributes, $values)
{
/** @var \Illuminate\Database\Eloquent\Model $model */
$model = static::firstOrNew($attributes);
$blankValues = collect($values)->filter(function ($fieldValue, $fieldName) use ($model) {
/** @var \Illuminate\Database\Eloquent\Model $model */
return blank($model->getAttribute($fieldName));
})->toArray();
$model->fill($blankValues)->save();
return $model;
}
}

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

Tags

Author

Written by Helmer Davila

In other languages

Estaba trabajando con Laravel y me encontré en la necesidad de actualizar solamente los campos vacíos en un modelo existente o crearlo si no existía. Existe el método updateOrCreate, pero no brinda ninguna ayuda para actualizar únicamente los campos que no estén llenos, sino todos los campos declarados, incluso si ya tienen valores.

Laravel - Actualizar sólo campos vacíos en un modelo

En Laravel, vous avez la méthode updateOrCreate. J’ai développé une application et j’ai besoin de mise a jour seulement le blank  propriétés. La logique était la suivante si l’enregistrement n’existe pas, le code devrait le créer.

Laravel - Seulement mise à jour des champs vides d’un modèle

Related posts

A function often used in many Laravel projects

Adonis JS: Using Laravel Mix function

Using the power of Mockery

Laravel Facades and Mockery, testing chained methods