vincent15000's avatar

Difference between model save and update methods

Hello,

I often see updates stores with the save method. For example Fortify use save instead of update.

class ResetUserPassword implements ResetsUserPasswords
{
    use PasswordValidationRules;

    /**
     * Validate and reset the user's forgotten password.
     *
     * @param  array<string, string>  $input
     */
    public function reset(User $user, array $input): void
    {
        Validator::make($input, [
            'password' => $this->passwordRules(),
        ])->validate();

        $user->forceFill([
            'password' => Hash::make($input['password']),
        ])->save();
    }
}

Why ?

Is there any logical reason ?

Thanks for your answer.

V

0 likes
4 replies
s4muel's avatar

in this particular example is it imho to use the forceFill(), otherwise the update() might not update the password if it is guarded/not fillable attribute

1 like
Snapey's avatar

for me it depends if the data I want to set is already an array

1 like
vincent15000's avatar

@Snapey @s4muel

No matter if it was for storing or updating, I always fill the model. Then if storing, I use save() and if updating, I use update().

$model->save();
$model->update();

Does the method impact the listeners when using an observer ?

tykus's avatar
tykus
Best Answer
Level 104

@vincent15000 the update Eloquent method delegates to save after (i) checking that the model actually exists and (ii) filling the model with the array of attributes provided (which is an empty array by default). So, there is no difference other than the semantics and that sanity check for existence

// vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
public function update(array $attributes = [], array $options = [])
{
    if (! $this->exists) {
        return false;
    }

    return $this->fill($attributes)->save($options);
}
1 like

Please or to participate in this conversation.