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

Godlove's avatar

Problems returning results from a many-to-many relation with Laravel and Mongodb

Greetings all, Please an new with mongodb and laravel and i want to implement a man-to-many relation. I have Student Model and Subject model, I want that many students can take a single subject and a single subject can be taken by many students. I created a pivot table called student_subjects table containing both student_id and subject_id as foreign keys and later realized that mongodb does not support pivot tables and now I am stock on the way forward with this. Thanks for the help in advance. GODLOVE.

0 likes
2 replies
claudsonm's avatar

You are using a non relational database and still thinking in a relational approach. Take a few steps back and figure out if you should really be using MongoDB for it.

As long as I know, in the NoSQL world you just store things directly in the document. For example, the document Student should be something like:

{
    "type": "Student",
    "name": "Jhon",
    "email": "[email protected]",
    "subjects_taken": ["calculus", "functional programming"]
}

The same goes for the Subject document.

{
    "type": "Subject",
    "name": "Calculus",
    "taken_by": ["jhon", "alice"]
}

I used strings, but people often use the _id attribute to make the "relation".

Hope it clarifies.

Please or to participate in this conversation.