Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

riki's avatar
Level 21

Using updateOrCreate() with incrementing value

Is it possible?

The code using NotORM library looks like this:

$this->database->$table->insert_update(
        $unique, array(), ['view' => new \NotORM_Literal('view + 1')]
);

0 likes
4 replies
quickliketurtle's avatar

Eloquent has both a findOrCreate and findOrNew method.

// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve the flight by the attributes, or instantiate a new instance...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

Maybe that will help? https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models

--Jeff

riki's avatar
Level 21

Yes, I used this but this query is very slow... It queries a statistics table with 17,592,468 rows with WHERE condition on multiple columns.

There is probably only one way to achieve this - using a raw command. The following SQL query is okay and working very quickly.

INSERT INTO stat_act (sub_id, act_id, exp_id, type_id, country_id, domain_id, date) 
VALUES ('19638', '166595', 0, 2, 151, 11, CURDATE()) ON DUPLICATE KEY 
UPDATE view = view + 1;

# Index: UNIQUE sub_id, act_id, exp_id, type_id, country_id, domain_id, date
djkarimi's avatar

Add new function code :)

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php :

public function updateOrInsert(array $attributes, array $values = [])
{
    $instance = $this->where($attributes);
    if ($instance->count() != 0) {
        $instance->update($values);
    } else {
        $instance = $this->updateOrCreate($attributes, $values);
    }
    return $instance;
}
1 like
dgpro's avatar

Just in case if anyone is looking for the same answer here is how it works with incrementing the value

$this->client
        ->query()
        ->table('mytable')
        ->updateOrInsert(
            [
                'key1' => $key1,
                'key2' => $key2,
            ],
            [
                'value' => \DB::raw('value + 1'),
            ]
        );
}
7 likes

Please or to participate in this conversation.