PHP
Efficiently Creating or Updating Eloquent Records
Master `firstOrCreate`, `updateOrCreate`, and `firstOrNew` in Laravel Eloquent to atomically retrieve, create, or update model instances.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['email', 'name', 'password'];
// ...
}
// --- Usage Examples ---
// 1. firstOrCreate(array $attributes, array $values = [])
// Attempts to find a record matching $attributes.
// If found, returns the model.
// If not found, creates a new record with $attributes and $values, then returns it.
$user = User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'Jane Doe', 'password' => bcrypt('password')]
);
// If a user with [email protected] exists, it's returned.
// Otherwise, a new user 'Jane Doe' is created with that email and password.
// 2. updateOrCreate(array $attributes, array $values = [])
// Attempts to find a record matching $attributes.
// If found, updates it with $values and returns the model.
// If not found, creates a new record with $attributes and $values, then returns it.
$updatedUser = User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'John Smith', 'password' => bcrypt('newpassword')]
);
// If '[email protected]' exists, its 'name' and 'password' are updated.
// Otherwise, a new user 'John Smith' is created.
// 3. firstOrNew(array $attributes, array $values = [])
// Attempts to find a record matching $attributes.
// If found, returns the model.
// If not found, returns a new model instance populated with $attributes and $values,
// but DOES NOT save it to the database yet. You must call $model->save() manually.
$userInstance = User::firstOrNew(
['email' => '[email protected]'],
['name' => 'New User', 'password' => bcrypt('temp_pass')]
);
if (!$userInstance->exists) {
$userInstance->save(); // Only saves if it was a new instance
}
// Useful when you want to perform additional operations or validations
// on the model before deciding to save it.
How it works: These methods provide powerful and atomic ways to manage model creation and updates. `firstOrCreate()` retrieves a model by its attributes or creates it if it doesn't exist. `updateOrCreate()` retrieves a model by its attributes or creates it, updating the record with additional values if it already exists. `firstOrNew()` retrieves an existing model or returns a new unsaved instance, allowing you to perform further actions before explicitly saving it. They are essential for handling scenarios like user registration or data synchronization where you need to avoid duplicate records while ensuring data presence.