Categories: Development

The Laravel updateOrCreate method

In Laravel the updateOrCreate() method is used when you want to perform an UPSERT which is to “UPDATE if key/s exists else do an INSERT”.

The method consists of 2 parameters, the first being key/s to match on and the second what columns and values get updated or inserted

updateOrCreate(array $attributes, array $values = [])

updateOrCreate() returns an Eloquent model.

In the example below if the id of ‘22076’ already exists then status, game_type, arena_id, home-id, visit_id and datetime will be updated if that id does not exist then these values will be inserted including the id.

$game = Game::updateOrCreate(
    [
        'id' => '22076'
    ],
    [
        'status' => 0,
        'game_type' => 2,
        'arena_id' => 11,
        'home_id' => 6,
        'visit_id' => 2,
        'datetime' => '2022-12-04 19:00:00'
    ]
);

The main usage case of an UPSERT is when you do not know if the row already exists in the database however if it does then update the values anyway.

UPSERT can help you avoid using INSERT IGNORE ... to which there is no Eloquent method for in Laravel.

Here more data is provided as the game is completed:

$game = Game::updateOrCreate(
    [
        'id' => '22076'
    ],
    [
        'status' => 0,
        'game_type' => 2,
        'arena_id' => 11,
        'home_id' => 6,
        'visit_id' => 2,
        'home_score' => 40,
        'visit_score' => 32,
        'winner_id' => 6,
        'datetime' => '2022-12-04 19:00:00'
    ]
);

Note that if the key already exists then only the second argument array is what gets updated compared to if it doesn’t exist then both argument arrays will be inserted.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago