php - Laravel Update if record exists or Create if not -
i want update record if exists create new 1 if not exists. here got far:
merchantbranch.php public function token() { return $this->hasone('app\merchantbranchtoken'); } merchantbranchtoken.php public function merchant_branch() { return $this->belongsto('app\merchantbranch'); } $find = merchantbranchtoken::find($id); if (!$find) { $branch = new merchantbranchtoken(['token' => $token]); merchantbranch::find($id)->token()->save($branch); } else { $find->token = $token; $find->save(); }
it's working perfectly.
but know laravel powerful eloquent model. can make shorter? or doing correctly?.
i've tried using "updateorcreate" method foreign key "merchant_branch_id" need fillable.
laravel using methodology save
function
$user->save()
laravel code
// if model exists in database can update our record // in database using current ids in "where" // clause update model. otherwise, we'll insert them. if ($this->exists) { $saved = $this->performupdate($query); } // if model brand new, we'll insert our database , set // id attribute on model value of newly inserted row's id // typically auto-increment value managed database. else { $saved = $this->performinsert($query); }
https://github.com/laravel/framework/blob/5.1/src/illuminate/database/eloquent/model.php#l1491
->exists
all laravel models have ->exists
property.
more if model either loaded database, or has been saved database since being created exists
property true; otherwise false.
if understand ->exists
can use here way deal such requirement.
another way.
/** * create or update record matching attributes, , fill values. * * @param array $attributes * @param array $values * @return static */ public static function updateorcreate(array $attributes, array $values = array()) { $instance = static::firstornew($attributes); $instance->fill($values)->save(); return $instance; }
Comments
Post a Comment