Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shadrix's avatar
Level 12

Can you load a relationship inside a pivot table?

Have a look first at this image. How would you solve the problem, when you have two pivot tables? Or would you solve it differently?

enter image description here

To make it more understandable. We have three "normal" models (User, Course and Lesson) and two Pivot tables (enrollments should actually be called course_user but I changed the name so it is more clear and enrollment_lesson).

Have a look at my problem. I cannot use the relationship here:

use Illuminate\Database\Eloquent\Relations\Pivot;

class Enrollment extends Pivot
{
    protected $guarded = [];

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = true;

    public function lessons()
    {
        return $this->belongsToMany(Lesson::class, 'enrollment_lesson', 'enrollment_id', 'lesson_id')
            ->using(EnrollmentLesson::class)
            ->as('enrolledLesson')
            ->withTimestamps();
    }
}

When I use it in phpunit:

$course->enrolledStudents()->first()->enrollment->lessons()->attach(1)

I get the error:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: enrollment_lesson.enrollment_id (SQL: insert into "enrollment_lesson" ("lesson_id", "enrollment_id", "created_at", "updated_at") values (1, ?, 2021-06-15 16:00:40, 2021-06-15 16:00:40))

Sorry about the image not having visible relationship arrows, but I think this should be clear. Thank you!

0 likes
2 replies
slavatar's avatar

Interesting issue actually. Just found such thing as a Pivot Model even existsts but there doesn't seem to be that much in the docs regarding to what you can do with it.

If loading a new relationship from the pivot model keeps refusing to work my instinct would go with making 'Enrollments' a separate Eloquent model. This model would then have a one to many relationship with both courses and users. Going that road you would have to do bits of funky stuff to wire up $course->users() and $user->courses but I'm pretty confident it would work in the end.

Still curious if there is a cleaner solution.

shadrix's avatar
Level 12

@slavatar Thanks for your fast reply! I was also thinking about separating the model but I hope to find a cleaner solution.

There is one solution that might work. I found it here. But I don't really want to use a third-party dependency. But I'm currently too tired to check if this is actually a solution 😂

1 like

Please or to participate in this conversation.