1

I have two models Customer, Contact with the following relationship in the Customer model:

public function latestContact () {
    return $this->hasOne(Contact::class)->latest();
}

I already found out here that the optional helper is a possible to way check if the relationship exists when displaying the data. Otherwise I would receive a "Trying to get property of non-object" error.

optional($customer->latestContact)->address

Now I am wondering if there is a way to directly check this inside the model function. I would prefer to only call

$customer->latestContact->address

or something like

$customer->getLatestContactAdress

and return false (or no result) if the relationship does not exists.

Thank you in advance.

maxiw46
  • 131
  • 1
  • 3
  • 11

2 Answers2

1

You could define an accessor or a function within your parent model.

Something like this in your Customer model:

public function getLatestContactAddress()
{
    return optional($this->latestContact)->address;
}

And call it like this:

$customer->getLatestContactAddress();
DevK
  • 9,597
  • 2
  • 26
  • 48
0

Try using eager loading

$customer = Customer::with('latestContact')->get();

Let me know if not works

afsal c
  • 612
  • 4
  • 12