Search code examples
phplaravelrelational-databaseeloquentrelationship

Can't get Laravel associate to work


I'm not quite sure if I understand the associate method in Laravel. I understand the idea, but I can't seem to get it to work.

With this (distilled) code:

class User
{

    public function customer()
    {
        return $this->hasOne('Customer');
    }

}

class Customer
{

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

}

$user = new User($data);
$customer = new Customer($customerData);

$user->customer()->associate($customer);

I get a Call to undefined method Illuminate\Database\Query\Builder::associate() when I try to run this.

From what I can read, I do it exactly as is stated in the docs.

What am I doing wrong?


Solution

  • I have to admit that when I first started using Laravel the relationships where the part that I had to consistently refer back to the docs for and even then in some cases I didn't quite get it right.

    To help you along, associate() is used to update a belongsTo() relationship. Looking at your code, the returned class from $user->customer() is a hasOne relationship class and will not have the associate method on it.

    If you were to do it the other way round.

    $user = new User($data);
    $customer = new Customer($customerData);
    
    $customer->user()->associate($user);
    $customer->save();
    

    It would work as $customer->user() is a belongsTo relationship.

    To do this the other way round you would first save the user model and then save the customer model to it like:

    $user = new User($data);
    $user->save();
    
    $customer = new Customer($customerData);
    $user->customer()->save($customer);
    

    Edit: It may not be necessary to save the user model first but I've just always done that, not sure why.