Get all records of relationship when parent doesn't exist

Viewed 58

I have two models.

Resource:

public function account()
{
    return $this->belongsTo('App\Account');
}

Account:

public function resources()
{
    return $this->hasMany('App\Resource');
}

I want to receive all resources of an account knowing user_id from account Model.

Account::where('user_id', Auth::id())->first()->resources()->get();

This works only when account exists. It throws error otherwise: Call to a member function resources() on null.

What's the smart way to get all resources in Eloquent? The best would be to use only one query statement in the background, because I know above example is using two queries.

1 Answers
Related