Chase Chase - 4 months ago 31
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 . '@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 'Ollie@positivelearning.com' for key 'users_email_unique' (SQL: insert into
`users` (`email`, `password`, `username`, `updated_at`, `created_at`) values (Ollie@positivelearning.com, 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'

Answer

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.

Comments