Laravel Eloquent updateOrCreate Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

In this short tutorial we will cover an laravel eloquent updateOrCreate. it's simple lesson of laravel model updateorcreate. This tutorial will give you simple lesson of laravel updateorcreate lesson. you can understand a concept of updateorcreate laravel lesson.

you can easily use eloquent updateOrCreate lesson 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 lessons, without updateOrCreate() and with updateOrCreate() lesson 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.

Recent Posts

Related Posts