← Back to all snippets
PHP

Efficiently Inserting or Updating Multiple Records with Eloquent Upsert

Use Laravel Eloquent's `upsert` method to perform atomic mass inserts or updates of records based on specified unique columns, improving database performance.

$users = [
    ['email' => '[email protected]', 'name' => 'John Doe', 'age' => 30],
    ['email' => '[email protected]', 'name' => 'Jane Smith', 'age' => 25],
    ['email' => '[email protected]', 'name' => 'John Updated', 'age' => 31], // This will update John
];

User::upsert($users, ['email'], ['name', 'age']);

// This will insert Jane Smith, and if '[email protected]' exists, it will update
// 'name' to 'John Updated' and 'age' to 31. If not, it will insert a new record for John.
How it works: The `upsert` method provides a highly efficient way to perform atomic mass inserts or updates of records in a single database query. It takes an array of data, a unique identifier column(s) (e.g., `email`) to check for existence, and an array of columns to update if a match is found. This is particularly useful for synchronizing data from external sources or handling large batch operations efficiently, minimizing database roundtrips.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs