Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
communitycreator

How to use updateOrInsert() in Laravel

Chinweuba Elijah Azubuike

Overview

In an E-commerce application where your user has already placed goods in the cart, but they have not yet updated their email in their profile, you will just send them to a page for them to update their email. If they are not yet registered, you just insert them into the database and continue the checkout process.

Normally, if they try to update their email when they are not registered your application, it will throw an error, but with updateOrInsert(), it will be inserted into the database.

What is updateOrInsert()?

updateOrInsert() is a query builder used to alter values of your database, in this case it either creates a new record or updates the existing record.

Syntax

DB::table('users')
    ->updateOrInsert();

Parameters

The updateOrInsert() method receives two parameters:

  1. Conditional array (to match existing record)
  2. Array of column name(s) and value to update or insert with

Example

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

Explanation

From the above code, you can see from the query structure how we chained the updateOrInsert() to the table() .

Look up my shot on How to use the table() for better understanding of the table() query builder.

Basically, we locate the table we want to update or insert the record into using the table(). In this case it is the users table. After that, we then chain the updateOrInsert()to it, and in the updateOrInsert() we pass a conditional array.

More details

In the first conditional array, ['email' => 'john@example.com', 'name' => 'John'] we are checking to see if the john@example.com record exist in the table. If the record does not exist, it is created, but if it exists, we would then update the vote column of the users table with 2, which is what the second array is carrying['votes' => '2'].

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;

class yourController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function updateUser(){
        DB::table('users')
            ->updateOrInsert(
                ['email' => 'john@example.com', 'name' => 'John'],
                ['votes' => '2']
            );
        return 'updated';
    }
}

RELATED TAGS

laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring