I'm using Route Model Binding to get a User instance then update it if validation passes, and then update the associated belongs to relationship between User and Profile, but I keep getting an error. The update occurs on the User, but fails on updating the Profile. From what I've understood from the docs this appears to be correct. I can access Profile data using $user->profile
so the relationship appears to be okay in the User and UserProfile models.
Can anyone see what is wrong with this controller action:
public function update(Request $request, User $user)
{
$this->validate($request, [
'username' => 'required|max:32|unique:users',
'email' => 'required|email|max:128|unique:users',
'first_name' => 'required',
'last_name' => 'required',
'phone_number' => 'regex:/^([0-9\s\-\+\(\)\.]*)$/',
]);
$user->update($request->all());
$profile = new UserProfile($request->all());
// Also tried:
//$profile = UserProfile::where(['user_id' => $user->id])->first();
$user->profile()->associate($profile);
$user->save();
return response()->json([
'message' => trans('user.updated'),
]);
}
Error
BadMethodCallException in Builder.php line 2161:
Call to undefined method Illuminate\Database\Query\Builder::associate()
User Model Relationships
/**
* A user has-one profile.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function profile()
{
return $this->hasOne('App\UserProfile');
}
UserProfile Model Relationship
/**
* A user profile belongs to a user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function user()
{
return $this->belongsTo('App\User');
}
Solution
$user->fill($request->all())->save();
$profile = UserProfile::where('user_id', $user->id)->first();
$profile->fill($request->all());
$user->profile()->save($profile);
You must retrieve or create new profile
entity first and put it in $profile
. Also, you have One-to-one relation here, so you should save your user's profile like this:
$user->profile()->save($profile);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With