Skip to content

Instantly share code, notes, and snippets.

@helmerdavila
Created October 20, 2018 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helmerdavila/9256432856ae4472b07afeb262f815a7 to your computer and use it in GitHub Desktop.
Save helmerdavila/9256432856ae4472b07afeb262f815a7 to your computer and use it in GitHub Desktop.
Secure Updatable
<?php
namespace App\Traits;
/**
* Trait SecureUpdatable
* Allows to secure update without override the existing fields in a model
* This dependes on the $fillable and $guarded attributes too
* @package 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment