PHP
Efficiently Upserting Records with Eloquent's updateOrCreate
Learn how to use Laravel Eloquent's `updateOrCreate` method to efficiently create a new record if it doesn't exist, or update it if it does, minimizing database queries.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function storeOrUpdate(Request $request)
{
$product = Product::updateOrCreate(
['sku' => $request->input('sku')], // Attributes to find by
[ // Attributes to set or update
'name' => $request->input('name'),
'price' => $request->input('price'),
'stock' => $request->input('stock', 0),
]
);
return response()->json($product);
}
}
How it works: The `updateOrCreate` method attempts to locate a database record using the first array of attributes. If a matching record is found, it will be updated with the attributes from the second array. If no matching record exists, a new record will be created with the combined attributes of both arrays. This method is highly efficient for upsert operations, reducing boilerplate code and database roundtrips.