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
Oct 22, 2024
4
Level 63
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
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.