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
- $user->profile() will return the relationship class such as Illuminate/Database/Eloquent/Relations/HasOne
- $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)
- https://github.com/laravel/framework/issues/13568
- https://github.com/laravel/framework/issues/2536
- Eloquent attach/detach/sync fires any event?
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
}