PHP

Efficiently Create or Update Records with `firstOrCreate` and `updateOrCreate`

Master Laravel Eloquent's `firstOrCreate` and `updateOrCreate` methods to atomically create a record if it doesn't exist, or update it if it does.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['email', 'name', 'password'];
}

// Using firstOrCreate: Retrieve a user by email, or create it if not found.
// The first array contains attributes to search by.
// The second array contains default attributes that will be used for creation if the record doesn't exist.
$user1 = User::firstOrCreate(
    ['email' => '[email protected]'],
    ['name' => 'John Doe', 'password' => bcrypt('password123')]
);
echo "User 1 ID: " . $user1->id . ", Name: " . $user1->name . " (Is new: " . ($user1->wasRecentlyCreated ? 'Yes' : 'No') . ")
";

// Using updateOrCreate: Find a user by email, update their name, or create them if not found.
// The first array is the attributes to search by.
// The second array is the attributes to update or create with.
$user2 = User::updateOrCreate(
    ['email' => '[email protected]'],
    ['name' => 'Jane Doe Updated', 'password' => bcrypt('new_password')]
);
echo "User 2 ID: " . $user2->id . ", Name: " . $user2->name . " (Is new: " . ($user2->wasRecentlyCreated ? 'Yes' : 'No') . ")
";

// Example of updating an existing record with updateOrCreate:
$user3 = User::updateOrCreate(
    ['email' => '[email protected]'], // Search by this
    ['name' => 'John A. Doe', 'password' => bcrypt('updated_password')]
); // Update with this if found, or create with both if not
echo "User 3 ID: " . $user3->id . ", Name: " . $user3->name . " (Is new: " . ($user3->wasRecentlyCreated ? 'Yes' : 'No') . ")
";
How it works: This snippet demonstrates `firstOrCreate` and `updateOrCreate`, two powerful Eloquent methods for handling common 'upsert' (update or insert) patterns. `firstOrCreate` attempts to find a record based on the first array of attributes; if not found, it creates one using both the first and second arrays. `updateOrCreate` searches by the first array; if found, it updates the record with attributes from the second array, otherwise it creates a new record using both arrays. These methods are atomic and help prevent race conditions, simplifying record management logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs