Tuesday, January 25, 2022

[FIXED] why my updateOrInsert doesn't work laravel

Issue

I use updateOrInsert to avoid duplicate data, why doesn't the Update function work and always insert data?

foreach($datas as $data){
                    DB::table('users')->updateOrInsert([
                        'user_connect_id' => $user->connect_id,
                        'description' => $data['description'],
                        'created_by' => $login->name,
                        'modified_by' => $login->name,
                        'created_at' => Carbon::now(),
                    ]);
                }

Solution

Check this out updateOrInsert, you need to two parameters, one is the matching attributes, the other is your array.

updateOrInsert(array $attributes, array $values = []) 

example:

DB::table('users')->updateOrInsert(['user_connect_id' => $user->connect_id],
                     [
                        'user_connect_id' => $user->connect_id,
                        'description' => $data['description'],
                        'created_by' => $login->name,
                        'modified_by' => $login->name,
                        'created_at' => Carbon::now(),
                     ]);


Answered By - TsaiKoga

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.