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.
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.
DB::table('users')
->updateOrInsert();
The updateOrInsert()
method receives two parameters:
DB::table('users')
->updateOrInsert(
['email' => 'john@example.com', 'name' => 'John'],
['votes' => '2']
);
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 thetable()
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.
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'; } }