0
votes

I've read the docs at https://laravel.com/docs/5.7/eloquent-relationships#eager-loading but am still having trouble.

Why does the else branch of this function not return a \App\Models\Customer object with an attached \App\Models\Contact?

/**
 * 
 * @param \App\Models\Contact $contact
 * @param string $msg
 * @return \App\Models\Customer
 */
public function createCustomerIfNecessary($contact, &$msg) {
    if ($contact->customer) {
        return $contact->customer;
    } else {
        $customer = new \App\Models\Customer();
        $customer->setUuid();
        $customer->contact_id = $contact->id;
        $customer->save();
        $customer->loadMissing('contact');
        $msg .= ' Created new customer with ID ' . $customer->id . '.';
        return $customer;
    }
}

Here is its test, which currently fails (ErrorException: Trying to get property 'id' of non-object on $resultCustomer):

public function testCreateCustomerIfNecessary() {
    $service = new \App\Services\OauthService();
    $msg = '';
    $contact = new \App\Models\Contact();
    $contactId = 654;
    $contact->id = $contactId;
    $resultCustomer = $service->createCustomerIfNecessary($contact, $msg);
    $this->assertEquals($contactId, $resultCustomer->contact->id);
}

P.S. The relationship works in other parts of my code.

The Contact model has:

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

And the Customer model has:

public function contact() {
    return $this->belongsTo('App\Models\Contact');
}

And the 'customers' table has a 'contact_id' foreign key.

1

1 Answers

1
votes

Ahhh, the next thing I tried after posting this question actually seems to work!

I replaced $customer->loadMissing('contact'); with $customer->contact()->associate($contact);

Now the test passes.