I have a User model that hasOne profile and $with=['profile']
I have a Profile model that belongsTo user and $touches=['user']
I can't get them to save properly and return the results I'm looking for.
In my UserAPI I'm trying to save a new or existing user:
$user->fill($data);
$user->save();
I have to save here since I do some other stuff that requires the user id.
Then I create the profile:
if ($user->profile) {
$profile = $user->profile;
} else {
$profile = new Models\Profile;
}
$profile->fill($data_profile);
The next bit is where I have the issue. I've tried a few different ways:
A)
if (!$user->profile) {
$profile->user()->associate($user);
$user->setRelation('profile', $profile);
}
$profile->save();
That causes $user->toArray() to crash due to an infinite loop serializing $user->profile->user->profile->etc
B)
$user->profile()->save($profile);
if (!$user->profile) {
$user->setRelation('profile', $profile);
}
But for some reason, before profile is save I have $user->profile but when saving $profile, it loads user which loads profile, so I get: $user->profile->user->profile But it stops there. I'm not sure why profile is loading user when it's saved. It only has a touch on the profile, not a with. Also, what caused me to notice all this to begin with, is it's not touching the user :/
C)
if (!$user->profile) {
$profile->user_id = $user->id;
$user->setRelation('profile', $profile);
}
$user->push();
This causes an infinite loop durring save, saves user, then profile, user, profile, etc.
It should work if it's a new user or a user update.
What am I doing wrong here?
A I got rid of a long while ago. B is what I've had but just realized it was loading extra stuff and editing the profile didn't update the user updated_at date, and C I just tried.
It's important that $profile touches $user.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community