Created
October 23, 2018 06:36
-
-
Save himan72/cfe4d4e322ec8e077c63f7a2b9d289ef to your computer and use it in GitHub Desktop.
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