1myb 1myb - 3 months ago 179x
PHP Question

Insert a new record if not exist and update if exist, laravel eloquent

Is there any shorthand for us to insert a new record if doesn't exist and update the record if exist? the following is the code i using.

$shopOwner = ShopMeta::where('shopId', '=', $theID)->where('metadataKey', '=', 2001)->first();
if ($shopOwner==null){
insert new record into database
} else {
update the existing record



Save function:


already do what you want...

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.
        $saved = $this->performInsert($query);