PHP
Efficiently Create or Update Records with updateOrCreate
Simplify your CRUD operations by using Laravel Eloquent's `updateOrCreate` method to atomically create a new record or update an existing one based on specified criteria.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function storeOrUpdate(Request $request)
{
// Define the attributes to search for (criteria to find a record)
$matchingAttributes = [
'sku' => $request->sku,
];
// Define the attributes to update or create (actual data)
$updateOrCreateAttributes = [
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'stock' => $request->stock,
];
// Find a product by SKU, or create it if not found.
// If found, update its other attributes.
$product = Product::updateOrCreate(
$matchingAttributes,
$updateOrCreateAttributes
);
return response()->json($product, 200);
}
}
// Example of a Product model (simplified):
// class Product extends Model
// {
// protected $fillable = ['sku', 'name', 'description', 'price', 'stock'];
// }
How it works: The `updateOrCreate` method is a powerful Eloquent feature that simplifies common 'upsert' operations. It accepts two arrays: the first contains the attributes used to locate a matching record (e.g., `sku`), and the second contains the attributes to be updated if a match is found, or used for creating a new record if no match exists. If a record matching the first array's criteria is found, it will be updated with the values from the second array. If no such record exists, a new record will be created using *all* attributes from both arrays combined. This ensures atomic creation or modification, preventing race conditions and simplifying your application logic.