Reputation: 137
I am trying to create a set of bogus users, using random string names, which I will later use the IDs for. I am running into an error where it isn't recognizing some of the variables I pass through. Below is my code:
$password = bcrypt($this->generateRandomString(15));
$user = User::firstOrNew([
'email' => ($firstName . '@company.com'),
'password' => $password,
'username' => $username,
'firstname' => $firstName,
'lastname' => $lastName,
]);
$user->save();
$userIds[] = $user->id;
I am using firstOrNew just in case a user with that random username has been already entered, in which case I'll just use its ID.
I know that $username
, $firstName
, and $lastName
all have data in those objects through testing, but for whatever reason, I get an error regarding a duplicate error on 'username'
because it believes that field is empty (''), even though I know my variable is not.
In other words, the SQL statement is only passing on the email and the password, and not the other three variables. Any thoughts?
Error message:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users_email_unique' (SQL: insert into
`users` (`email`, `password`, `username`, `updated_at`, `created_at`) values ([email protected], y$rx8R0N5dVAibjpXxV0OF4uGGb7lradsl2xME
20ymMvv2YPaUWv3oq, olliepritsak, 2016-07-14 18:10:10, 2016-07-14 18:10:10))
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_username_unique'
Upvotes: 0
Views: 676
Reputation: 544
Method firstOrNew()
is attempting to locate a database record using all the given column / value pairs. You should only use the attributes that make an unique key, like email, for instance.
Then you will want to check for the model's exists
property to fill in the remaining fields if the model is new (exists
is false) and save it.
Upvotes: 1
Reputation: 5367
Okay, so based on the error (your original error posted)...doesn't look like you're passing the following values, 'username' => $username, 'firstname' => $firstName, 'lastname' => $lastName,
...
Make sure in your User
model, you have these under fillable
, like so:
protected $fillable = [
...
'username',
'firstname',
'lastname',
];
I think this is where your problem is stemming from.
Upvotes: 2