ItSolutionStuff.com

Laravel Eloquent updateOrCreate Example

By Hardik Savani • April 16, 2024
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.

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent firstOrCreate Example

Read Now →

PHP Laravel Inner Join Query Example

Read Now →

Laravel Eloquent take() and skip() Query Example

Read Now →

Laravel Eloquent whereNull() Query Example

Read Now →

Laravel Eloquent whereBetween() Query Example

Read Now →

Multiple orWhere Condition in Laravel Eloquent

Read Now →

Laravel Collection Flatten Method Example

Read Now →

Laravel Collection Duplicates Method Example

Read Now →

Laravel Collection GroupBy with Examples

Read Now →

How to use Union Query with Laravel Eloquent?

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →