3

When we inserting or updating the data via Eloquent relationship model, which is the best approach to use?

Example

$user->profile->update(['salary' => 5000]);

vs
 
$user->profile()->update(['salary' => 5000]);

I understand that

  1. $user->profile() will return the relationship class such as Illuminate/Database/Eloquent/Relations/HasOne
  2. $user->profile will return the actual UserProfile model class

I somehow remember I saw someone recommended to use $user->profile->update() instead of $user->profile()->update() but I couldn't find the article or reference link anymore

However, I found that if $user->profile is null, then it might caused an error such as

Call to a member function update() on null

So will it be easier to use relationship function update all the time?

$user->profile()->create()
$user->profile()->update()
$user->profile()->save()
$user->profile()->delete()

Is there any situation we should use the $user->profile->save() instead?

Or should one use it when it is in the multiple nested relationship?

$user->profile->bank()->create()
$user->profile()->bank()->create()

Update

reference link (for my own understanding)

Conclusion

For now, will use code below in application, both will trigger events

if ($user->bank === null) {
    $user->bank()->save(new UserBankAccount($input)); // trigger created event
    // $user->bank()->create($input);// trigger created event
} else {
    $user->bank->update($input); // trigger updated event
    // $user->bank()->update($input); // will NOT trigger updated event
}
cww
  • 593
  • 1
  • 8
  • 16
  • 1
    if you are on php8 you can use an null save method call `$user->profile?->update()` – Spirit Jan 03 '22 at 19:05
  • 1
    thought that issue looked familiar ... glad i won't have to explain all that again `;)` – lagbox Jan 03 '22 at 19:27
  • yeah, I am trying to write down the scenarios of each methods and pros and cons, so I could avoid making this mistakes in my code. – cww Jan 03 '22 at 19:33
  • 2
    not sure if it is mentioned in the issues but one method will involve eloquent events and the other will not ... when calling `update` on a model instance will cause model events to be fired as `save` is called; the other method is a direct `update` call on the builder so no model events – lagbox Jan 03 '22 at 19:34
  • 1
    Thanks, your comments is exactly the answer that what I looking for. :) – cww Jan 03 '22 at 19:36

1 Answers1

0

You can use forceFill()

Example:

$user->bank->forceFill($data)->save();
hbakouane
  • 21
  • 1
  • 5