Realtionships that require an authenticated User

Posted 9 months ago by JayBird

Say you have a User Model.

You also have a Products Model.

Users can create private notes about products.

When getting all the products, I want to eager load the notes for each product for the currently authenticated user.

I am currently doing it like this...

public function notes()
    if (! auth()->check()) {
        throw new \Exception('You cannot use the '.__METHOD__.' relationship when there is no authenticated user.');

    return $this->hasOne(Notes::class, 'product_id', 'product_id')->where('userID', auth()->user()->userID);

It works fine, but seems a little messy.

Is there a better way?


Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.