Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel return empty relationship on model when condidtion is true

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?

like image 417
Troyer Avatar asked Dec 02 '22 11:12

Troyer


2 Answers

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');
        }

    });

}
like image 121
Lionel Chan Avatar answered Dec 23 '22 11:12

Lionel Chan


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');
}
like image 35
pablorsk Avatar answered Dec 23 '22 11:12

pablorsk