PHP
Efficiently Creating or Updating Records with Eloquent `updateOrCreate`
Master Laravel Eloquent's `updateOrCreate` method to atomically insert a new record or update an existing one based on specified attributes, simplifying data synchronization.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['sku', 'name', 'price', 'description'];
}
// Scenario 1: Product with SKU 'PROD123' exists - it will be updated.
$product1 = Product::updateOrCreate(
['sku' => 'PROD123'], // Search attributes
['name' => 'Premium Widget Pro', 'price' => 39.99] // Attributes to update or create with
);
echo "Product 1 ID: " . $product1->id . " (Status: " . ($product1->wasRecentlyCreated ? 'Created' : 'Updated') . ")
";
// Scenario 2: Product with SKU 'PROD456' does not exist - a new one will be created.
$product2 = Product::updateOrCreate(
['sku' => 'PROD456'],
['name' => 'Standard Gadget', 'price' => 9.99, 'description' => 'A basic gadget.']
);
echo "Product 2 ID: " . $product2->id . " (Status: " . ($product2->wasRecentlyCreated ? 'Created' : 'Updated') . ")
";
How it works: The `updateOrCreate` method in Laravel Eloquent provides a convenient way to either update an existing database record or create a new one if it doesn't exist. It takes two arrays as arguments: the first array contains attributes used to find a matching record, and the second array contains attributes to update the record with if found, or to create the new record with if not found. This method is atomic and ideal for synchronization tasks where you want to avoid duplicate entries and handle both creation and modification in a single operation.