inuShiva
inuShiva

Reputation: 173

WhereHas On Relationship Instance in Model

I have the following issue, where I want to define a specific attribute rather than querying it through a controller every time. But at the moment, I'm not sure where to go as whereHas does not work with collections.

Currently my model attribute looks like this:

public function getPrimaryBillingContactAttribute(){
  $primaryBillingContact = $this->contacts->whereHas('contactType', function ($query) {
      $query->where('id', '=', '2');
  })->first();
  return $primaryBillingContact;
}

If necessary, I will go through the controllers just fine, I was just hoping to define a working global attribute for my Customer model.

Thanks!

Upvotes: 1

Views: 312

Answers (1)

mrhn
mrhn

Reputation: 18926

I do not think the global variable is the correct way and since you can not do this in a query for now. But for your convenience i converted the whereHas to a collection method that does the same, as i seem to be your main problem and should get the attribute getter to work.

$this->contacts->filter(function (Contact $contact) {
    return $contact->contactType->id === 2;
})->first();

Basically loops through all contacts on a condition, that condition is only to return contacts with the contact type with id 2. And take the first one, exactly like the whereHas does. I hope this is enough to help you forward.

Upvotes: 1

Related Questions