Sapnesh Naik
Sapnesh Naik

Reputation: 11656

Model::create() method considers only the original request value when creating a record

I am trying to create a record by passing the request object as an array like

    User::create($request->toArray());

This works fine and the record is created in the table.

But I need to manipulate a field before creating the record,

    $request->password = bcrypt($request->password);

    //echo $request->password;
    User::create($request->toArray());

This does not work and the record created in the table still has the old unencrypted value.
I can confirm that $request->password does have the encrypted value. There seems to be something going on in $request->toArray() call.

What am I missing here?

Upvotes: 1

Views: 31

Answers (2)

Prince Lionel N'zi
Prince Lionel N'zi

Reputation: 2588

You can array_merge add the password to the $request->toArray()

$password = bcrypt($request->password);

$data = array_merge($request->toArray(), compact('password'))

User::create($data);

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163928

You can just change Request object, but you can do this:

User::create(['password' => bcrypt($request->password)] + $request->all());

But a better approach is to use a mutator for password property:

public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value);
}

Then just do this:

User::create($request->all());

Upvotes: 1

Related Questions