Duplicate entry while using updateOrCreate()

Viewed 1976

I'm using (latest) Lumen, which could be the culprit to my error.

When I'm using updateOrCreate():

            User::updateOrCreate(
            ['username'     => $user->username],
            [
                'email'         => $user->email,
                'password'      => $user->password,
                'foreign_id'    => $user->foreign_id,                
                'client_id'     => $user->client_id,
                'status'        => $user->active,
                'user_level'    => (integer) $user->user_level
            ]
        );

on one of my models, I get mysql error:

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'user@name.com' for key 'users_username_unique' (SQL: insert into `users` (`username`,

because it tries to insert duplicate value for one of my unique columns (username).

So, function itself exists, I dont get any errors, and it works for first inserts, but once it reaches functionality of checking if DB entry exists and needs only to update it, it still wants to create new entry, but with duplicated value.

Laravel itself has updateOrCreate(): https://laravel.com/docs/8.x/eloquent#upserts in its Eloquent. Is Eloquent in Lumen somehow crippled on this function?

When looking through the code of Laravel or Lumen, I cannot find this function implemented, the closest is updateOrFail()...

1 Answers
User::updateOrCreate(
        [
            'username'     => $user->username,
            'foreign_id'    => $user->foreign_id
        ],

        [
            'email'         => $user->email,
            'password'      => $user->password,                                
            'client_id'     => $user->client_id,
            'status'        => $user->active,
            'user_level'    => (integer) $user->user_level
        ])

// first array must contains all the primary/composite keys which makes the it a unique records

Related