Laravel Eloquent updateOrCreate Example

By Hardik Savani | January 12, 2021 | 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 and laravel 8 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
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: