Laravel Eloquent updateOrCreate Example

By Hardik Savani April 16, 2024 Category : Laravel

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.

Shares