Laravel Eloquent updateOrCreate Example
In this short tutorial we will cover an laravel eloquent updateOrCreate. it's simple example of laravel model updateorcreate. This tutorial will give you simple example of laravel updateorcreate example. you can understand a concept of updateorcreate laravel example.
you can easily use eloquent updateOrCreate example in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.
Laravel eloquent added amazing method call updateOrCreate(). updateOrCreate method help you to check if record is exist then it will update otherwise create new record.
I will show you simple examples, without updateOrCreate() and with updateOrCreate() example so you will understand how it's helps you.
Without using updateOrCreate()
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$name = 'Platinum';
$product = Product::where('name', $name)->first();
if (!is_null($product)) {
$product->update([
'price' => 130,
'price_update_date' => date('Y-m-d')
]);
}else{
$product = Product::create([
'name' => 'Platinum',
'price' => 130,
'price_update_date' => date('Y-m-d')
]);
}
dd($product);
}
}
With using firstOrCreate()
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$product = Product::updateOrCreate(
[ 'name' => 'Platinum' ],
[ 'price' => 130, 'price_update_date' => date('Y-m-d') ]
);
dd($product);
}
}
I hope you will understand how it works and how it helps you.
i hope it can help you.
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent firstOrCreate Example
- PHP Laravel Inner Join Query Example
- Laravel Eloquent take() and skip() Query Example
- Laravel Eloquent whereNull() Query Example
- Laravel Eloquent whereBetween() Query Example
- Multiple orWhere Condition in Laravel Eloquent
- Laravel Collection Flatten Method Example
- Laravel Collection Duplicates Method Example
- Laravel Collection GroupBy with Examples
- How to use Union Query with Laravel Eloquent?
- Laravel Many to Many Eloquent Relationship Tutorial