How to use updateOrCreate() Query in Laravel ?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
Laravel updateOrCreate() Query

Today now in this post ,I will show you how you can use laravel provides an updateorcreate method in application. Here we are use updateOrCreate method for database create new recored or if the recored is already exists then it will be update recored. So here I will show you laravel updateorcreate() query example.

Here you may come for across situations where you want to update an existing data or you want create a new data if none exists. Then Laravel provides us an updateOrCreate method to do this in just one step.

So here is the example of updateOrCreate method.

Example

Now here you can learn the following updateOrCreate mehtod example. So here i will show table records before updateorcreate method we are use.

Now so here the blow updateorcreate method to create recoreds

Create Recoreds by Using updateorcreate Method

So here updateorcreate Method by using create recoreds.

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    $user = ["name" => "Pqr",
            "email" => "Pqr@gmail.com",
            "password" => bcrypt('123456'),
            "country" => "india",
            ];

    $userInformation = ["state" => "Gujarat","temperature" => "10"];

    User::updateOrCreate($user,$userInformation);
    dd("suucessfull");
}
Update Recoreds Using updateorcreate Method

Now here updateorcreate Method by using update records.

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    $user = ["name" => "Pqr",
            "email" => "Pqr@gmail.com",
            "password" => bcrypt('123456'),
            "country" => "india",
            ];

    $userInformation = ["state" => "Gujarat","temperature" => "16"];

    User::updateOrCreate($user,$userInformation);
    dd("suucessfull");
}

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →