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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago