dmelo320's avatar

Call to undefined method, associate method

Hello, when I use associate, I get this error

BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\HasOne::associate()

Controller

/**
     * Create new user.
     * @param $request
     */
    public function createUser($request)
    {
        try {

            $user = $this->user->fill([
                'name' => $request->name,
                'email' => $request->email,
                'phone_number' => $request->phone_number,
                'accept_term' => $request->accept_term,
                'password' => Hash::make($request->password),
            ]);

            $address = $this->address->fill([
                'street' => $request->street,
                'number' => $request->number,
                'zip_code' => $request->zip_code,
            ]);

                $user->address()->associate($address);
                $user->save();

            return $user;
            
        } catch (\RuntimeException $exception) {
            return ['error' => $exception->getMessage()];
        }
    }

Model User

public function address()
    {
        return $this->hasOne('App\Entities\Address');
    }

Model Address

public function user()
    {
        return $this->belongsTo('App\Entities\User');
    }
0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

associate() is used in a belongsTo() relationship, not hasOne(). Use save() instead of associate. You'll want to save the user first though.

  1. create user and save user
  2. create the address and save it for the user $user->address()->save($address);
1 like
dmelo320's avatar

Thank you, I was doing the wrong thing.

Please or to participate in this conversation.