I have a model where I want to return a empty value when a condition happens, but when I try to get the model:
Model::with('shop')->find(id);
I get this error:
"Call to a member function addEagerConstraints() on null"
This is the code I'm trying:
public function shop(){
if(true) {
return null;
}
return $this->belongsTo('App\Models\Shop');
}
How is the proper way to return nothing when a condition is true on Laravel relationships?
I think you could use this trick - set an impossible query condition when a condition met:
public function shop(){
return $this->belongsTo('App\Models\Shop')->where(function($query) {
if ($condition) {
// I think this should do the trick
$query->whereNull('id');
}
});
}
Correct way to return a BelongsTo
instance.
public function shop(): BelongsTo
{
if(true) {
return new BelongsTo($this->newQuery(), $this, '', '', '');
}
return $this->belongsTo('App\Models\Shop');
}
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