dimanche 13 mars 2016

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' => 'http://regex:/^([0-9\s\-\+\(\)\.]*)$/',
    ]);

    $user->update($request->all());
    $user->profile()->associate($request->all());
    $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()



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire