Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Update if record exists or Create if not

I want to update my record if it exists but create new one if not exists. here is i got so 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 as i know Laravel is very powerful for its eloquent model. Can I make it shorter? or i already doing it correctly?.

I've tried using "updateOrCreate" method but my foreign key "merchant_branch_id" need to be fillable.

like image 204
ssuhat Avatar asked Oct 15 '15 02:10

ssuhat


2 Answers

Laravel provide method updateOrCreate for that purpose

  • If there's a flight from Oakland to San Diego, set the price to $99.

  • If no matching model exists, create one.

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);
like image 101
tuananh Avatar answered Nov 02 '22 11:11

tuananh


Laravel already using this methodology by save function

$user->save()

Laravel Code

// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists)
{
    $saved = $this->performUpdate($query);
}

// If the model is brand new, we'll insert it into our database and set the
// ID attribute on the model to the value of the newly inserted row's ID
// which is typically an auto-increment value managed by the 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 a ->exists property.

More specifically if the model is either loaded from the database, or has been saved to the database since being created the exists property will be true; Otherwise it will be false.

If you understand the ->exists you can use it but here is the another way to deal such requirement.

another way.

/**
     * Create or update a record matching the attributes, and fill it with 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;
    }
like image 7
Safoor Safdar Avatar answered Nov 02 '22 11:11

Safoor Safdar