Laravel how to create empty relationship?

Viewed 762

I have a condition inside a relationship where if the user is logged in it will return the relation and if not i want it to return empty relationship. here is what i want :

public function dummy()
{
    return (auth()->user()) ? $this->hasOne(blah::class) : emptyrelationship();
}
5 Answers

Try This example

public function shop(){
    if(true) {
        return $this->newQuery(); // or newQueryWithoutScopes()
    }
    return $this->belongsTo('App\Models\Shop');
}

To return an empty relationship instead of null, you can try this:

public function item()
{
    return $this->belongsTo(Item::class)
        ->withDefault(function () {
            return new Item();
        });
}

If there is no user in the user table collection will return relationship as "relationship: user: []" as blank only if you do dd($var) on your query,then you can check though conditions in your code;

Eloquent has a method for that newModelInstance

Best to keep the eloquent model standard relationship and move logic elsewhere

public function dummy()
{
    return $this->hasOne(blah::class);
}

$dummy = $model->dummy;
if (!$dummy) {
    $dummy = $model->dummy()->newModelInstance();
}
Related