Say I have a Model, and I want to return a relationship, but it depends on a value of an attribute of the model. I tried this in my model:
public function paymentType(){
if($this->type > 1) return $this->hasOne(PaymentType::class, 'type', 'type');
if($this->type == 1) return $this->hasOne(PaymentType::class, 'payment_type', 'pay_type');
}
When I have an instance of the model, I can call this relationship fine, however when I try to eager load, and call with('paymentType')
, I get the exception Call to a member function addEagerConstraints() on null
I would imagine that your issue with eager loading arises because the models are not yet populated with values. Trying to check for a model's type with $this->type
goes against the nature of eager loading.
You options are to:
A) Use lazy loading so that type
is populated in the model before you call the relationship, or
B) Use eager loading constraints
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With