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.