How to update in one to one relation in laravel?

In my user model, I have the following code

public function profile()
{
    return $this->hasOne(UserProfile::class);
}

In profile model,

public function user()
{
   return $this->belongsTo(User::class);
}

The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.

$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';

$user = User::find($userId);
$res = $user->profile()->save($profile);

What is the correct method to update in One to One Relationship ?

Upvotes: 0

Views: 695

Answers (3)

I fixed it using push method. Here is the code.

$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();

Upvotes: 1

PHP Geek
PHP Geek

Reputation: 4033

you are using save method to save new record. use update query

//controller
$userObj=new User();
if(!empty($userId) && $userId!=null){
$userObj->updateByUserId($userId,[
'dob' = '1999-03-20';
'bio' = 'A professional programmer.';
'facebook' = 'http://facebook.com/test/1';
'github' = 'http://github.com/test/1';
'twitter' = 'http://twitter.com/test/1';
]);
}

//model
function updateByUserId($userId,$updateArray){
return $this->where('user_id',$userId)->update($updateArray);
}

Upvotes: 0

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

You're doing right, however i could suggest a little improvement

You may use the following

$user = User::with('profile')->findOrFail($userId);

if ($user->profile === null)
{
    $profile = new UserProfile(['attr' => 'value', ....]);
    $user->profile()->save($profile);
}
else
{
    $user->profile()->update(['attr' => 'value', ....]);
}

Upvotes: 0

Related Questions