DEV Community

Victor Basumatary
Victor Basumatary

Posted on

1

Laravel Relationship Gotcha

Laravel is nice. It lets you define relationships painlessly.

// app/MultipleChoiceQuestion.php
class MultipleChoiceQuestion extends Model
{
    public function answers()
    {
        return $this->hasMany(\App\Answer::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

We can even make relationships in the other direction.

// app/Answer.php
class Answer extends Model
{
    public function question()
    {
        return $this->belongsTo(\App\MultipleChoiceQuestion::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

If we know we're often going to query for the answers to our questions when we query for the questions, it makes sense to eager load them by default.

// app/MultipleChoiceQuestion.php
class MultipleChoiceQuestion extends Model
{
    protected $with = ['answers'];

    public function answers()
    {
        return $this->hasMany(\App\Answer::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

But what happens when we eager load the question on the answer as well?

// app/Answer.php
class Answer extends Model
{
    protected $with = ['question'];

    public function question()
    {
        return $this->belongsTo(\App\MultipleChoiceQuestion::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

Chaos. When you query the question you query for its answers as well which in turn queries for the question they belongs to and...

Your relationships must terminate somewhere.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay