Generally, in Laravel, we use the create() method to create new data and the update() method to update our data into the database.

But there is a way to use both methods at a time like when it needs to create new data it uses the create() method and to update the data it uses the update().

In this tutorial, you are going to learn how to use the updateOrCreate() method in Laravel.

Let’s think, we have a database table named votes in our database where we can store the number of votes according to the candidate. Here are our database table fields.

public function up()
{
    Schema::create('candidates', function (Blueprint $table) {
        $table->id();
        $table->string('candidate_id');
        $table->integer('votes');
        $table->timestamps();
    });
}

Now, if we use the typical way to create and update data, we can do like this-

public function update(Request $request){

    foreach($request->votes as $candidate_id => $votes){
        $vote = Vote::where('candidate_id', $candidate_id)->first();
        if($vote) {
            $vote->update(['votes'] => $votes]);
        } else {
            Vote::create(['candidate_id' => $candidate_id, 'votes' => $votes]);
        }
    }
    return redirect()->route('vote.index');
}

We simply performed a foreach loop to receive the user requests and call the Vote model. Then we check if the id and data already exists or not. If exists it’s data can be updated and if not, it can create a new data. But you can see that, it is long way.

Now, we can skip all those codes and use just one method called the updateOrCreate() to perform the same operations.

public function update(Request $request){

    foreach($request->votes as $candidate_id => $votes){
        Vote::updateOrCreate(
            ['candidate_id' => $candidate_id],
            ['votes' => $votes]
        );
    }
    return redirect()->route('vote.index');
}

The updateOrCreate() method takes two parameters. The first one defines what to search by and the second one defines what needs to update. In our case, it is the candidate_id and the votes. Let’s see the output-

OUTPUT:

Create:

Here, in the votes table, we have created three candidates with their number of votes.

Here, we inserted the fourth data and notice that the first three data didn’t change a bit.

Update:

Now, we updated id 1 and set its number of votes to 50. You can see that the other three data remain the same.

Note: When we use the Eloquent Builder we need the updateOrCreate() method and for Query Builder, we have to use the updateOrInsert() method. But they work the same.

Now, why do we have to use the updateOrCreate() method? While we can do the same work in a traditional way. The answer is, the updateOrCreate() method reduces the number of queries and the load time. It also increases the performance of the operation. So, in this tutorial, you learned, how to use the updateOrCreate() method. Thank you.