Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Using Associate to Update a BelongsTo Relationship

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);
like image 881
mtpultz Avatar asked Sep 17 '25 16:09

mtpultz


1 Answers

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);
like image 81
Alexey Mezenin Avatar answered Sep 19 '25 05:09

Alexey Mezenin