Created
October 20, 2018 06:29
-
-
Save helmerdavila/9256432856ae4472b07afeb262f815a7 to your computer and use it in GitHub Desktop.
Secure Updatable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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