Ash Ash - 7 months ago 50
PHP Question

Laravel Eloquent: How to store model values before saving?

I have a custom function within one of my models. It looks like this:

public function newWithTeam($data, $team_id = false){

$levels = Permissions::get_levels();

$this->email = $data['email'];
$this->password = bcrypt($data['password']);
$this->username = $data['username'];

$this->save();

$profile = new Profile(['name' => $data['name'],'bio' => $data['bio']]);
$this->profile()->save($profile);
}


Here, you can see I store the
email
,
password
and
username
as object properties, before hitting
save()


Instead, I'd like to do this in one line, something like:

$this->store(['email' => $data['email], 'password' => $data['password], 'username' => $data['username']]);

$this->save();


I am aware that the
create()
method exists, but when I use this, the following line
$this->profile()->save($profile);
does not work properly. I think the
create()
function does not work the same as
save()
for some reason! Is there any equivalent to the
store()
function as above?

Answer

The method that You're looking for is fill:

$this->fill([
    'email' => $data['email'],
    'password' => $data['password'],
    'username' => $data['username']]
);
$this->save();

You can use it for both creating and updating.