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.
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]
);
Laravel already using this methodology by save
function
$user->save()
// 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.
/**
* 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With