I've created a table named: staff in the database.
Inside that table, there are: id, staffID, staffName, role, and password which the id field is autoincrement(its mean primary Key), and the staffID is Unique Key.
After that, I inserted a few data. For example: , 69, habie, admin, 123456
the problem is when i tried to inserting new datas, for example:
| , 69, habie, admin, 2010201 | , 70, rafif, finance, 808080 | , 71, rizieq, sales, 737373 |
I'll getting an error code, which the error message is:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '69' for key 'staffID' (SQL: insert into
staff
(staffID
,staffName
,role
,password
) values (69, Habie, admin, 2010201))
I've tried many steps for solving this problem. For example:
I used: firstOrCreate Method, firstOrNew Method, and updateOrCreate Method from laravel eloquent class. but it has no effect.
$this::firstOrCreate([
"staffID" =>$staff["PIN2"],
"staffName" =>$staff["Name"],
"role" =>$staff["Privilege"],
"password" =>$pass
]);
I just want my table is get update if the same key unique has a new password, etc. And if there are new datas, laravel inserting that new data into database. I hope someone can help me out.
First of all, you are using firstOrCreate()
method in wrong way. If staffID
is unique, you have to use it in the following way.
$starff = $this::firstOrCreate([
"staffID" =>$staff["PIN2"],
],
[
"staffName" =>$staff["Name"],
"role" =>$staff["Privilege"],
]);
// Update password
$staff->password = $pass;
$staff->save();
This will check fir staffID
and create a new if don't exists. Then you can update the password or other things details.