Laravel Eloquent updateOrCreate Query Example
Today, we will learn Laravel Eloquent updateOrCreate Query Example. Laravel eloquent added amazing method call updateOrCreate(). updateOrCreate method is used to check if the record exists then it will update otherwise new record is created. We use Laravel Eloquent use updateOrCreate() Query functionality. Laravel default provides Eloquent updateOrCreate() method.
Also read: Laravel Eloquent union() Query
let’s start to see the below examples that will help you how to use without updateOrCreate() and with updateOrCreate() eloquent query example.
Also read: Laravel Eloquent whereNull() and whereNotNull() Query
Without using updateOrCreate()
<?php #app\Http\Controllers\ProductController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Product; class ProductController extends Controller { public function index() { $name = 'Iphone 12'; $product = Product::where('name', $name)->first(); if(!is_null($product)) { $product->update([ 'price' => 76000, 'price_updated_date' => date('Y-m-d') ]); } else { $product = Product::create([ 'name' => $name, 'price' => 76000, 'price_updated_date' => date('Y-m-d') ]); } dd($product); } }
Also read: Laravel eloquent firstOrCreate example
With using updateOrCreate()
<?php #app\Http\Controllers\ProductController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Product; class ProductController extends Controller { public function index() { $product = Product::updateOrCreate( [ 'name' => 'Iphone 12' ], [ 'price' => 76000, 'price_updated_date' => date('Y-m-d') ] ); dd($product); } }
Also read: Laravel Eloquent whereNotBetween() Example