aBhijit
aBhijit

Reputation: 5391

Laravel - Updating OneToOne relationship

I have two models 'User' and 'Profile'.

'email' field is in User model whereas 'name' field is in Profile model.

'profiles' table has a foreign key of 'user_id'.

I searched a lot but couldn't find a proper solution on how I can update both of these entities in one go.

In my ProfileController, I am doing this but I am sure there is a better way. Please help.

public function update($id)
{
    $profile = Profile::where('id', $id);
    $profile->name = 'Jon';
    $profile->save();

    $user = User::where('id', $profile->user_id);
    $user->email = '[email protected]';
    $user->save();
}

My Profile model has

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

And my User model has

public function profile()
{
    return $this->hasOne('Profile');
}

Upvotes: 0

Views: 209

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

You can't do it in one go.

However you could simplify it a bit, by leveraging Laravel features, like this (and do it in one-go-like way):

1 Controller edit

$profile = Profile::with('user')->find($id); 
// make sure you eager load the user for below to work

2 View

{{ Form::model($profile) }}
  {{ Form::text('name') }}
  {{ Form::text('user[email]') }}
{{ Form::close() }}

this will autopopulate your profile data (and user data too)

3 Controller update

$profile = Profile::find($id);
$profile->fill(Input::only(.. fields you want to update ..));
$profile->user->fill(Input::get('user')); // array of user data form the form
$profile->push(); // save both models in one go BUT separate queries

Also make sure you have fillable on your models, so fill will does its job.


Another way would be using model events, but I wouldn't do it that way.

Upvotes: 4

Related Questions