Chase Chase - 1 year ago 150
PHP Question

Eloquent firstOrNew() query not recognizing parameters passed to it

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 . ''),
'password' => $password,
'username' => $username,
'firstname' => $firstName,
'lastname' => $lastName,
$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
, and
all have data in those objects through testing, but for whatever reason, I get an error regarding a duplicate error on
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:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_email_unique' (SQL: insert into
`users` (`email`, `password`, `username`, `updated_at`, `created_at`) values (, y$rx8R0N5dVAibjpXxV0OF4uGGb7lradsl2xME
20ymMvv2YPaUWv3oq, olliepritsak, 2016-07-14 18:10:10, 2016-07-14 18:10:10))

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_username_unique'

Answer Source

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 = [

I think this is where your problem is stemming from.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download