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

Elver's avatar
Level 1

Laravel relationship not working as expected

I have a User model that applies both for trainers and studenst. In my business logic Trainers have students assigned for a certain Unit, so i built a many-to-many relationship among them

    public function students()
    {
        return $this->belongsToMany(User::class, 'trainer_student', 'trainer_id','student_id');
    }

        public function trainers()
    {
        return $this->belongsToMany(User::class, 'trainer_student','student_id', 'trainer_id');
    }

Both in the User model. I checked the DB and there are 8 students related to a trainer for a certain Unit.

"trainer_student" Table Photo.

So i did this query with Tinker:

    $trainer = User::findOrFail(21);
    $trainer->students()->pluck('id');

Output.

But if i query like the usual way:

DB::table('trainer_student')->where('trainer_id',21)->pluck('student_id')

Output.

What is going on? Why the relationship shows less students? What am i doing wrong?

Thanks!

0 likes
4 replies
Cronix's avatar

On the first one, you are plucking id, on the 2nd one you are plucking student_id?

1 like
Cronix's avatar

Wouldn't it be hasMany() relationships on the Trainer model? A trainer has many students? And on the Student model, a student belongsTo a trainer?

I don't know what the trainers() relationship is for. Is that on the Trainer model?

Elver's avatar
Level 1

First: Yes, i'm querying different tables, firstly Users table, which has "id" for a certain user, and then "trainer_students" which has "student_id" for a certain student...we are talking about different tables...

Second: A trainer can have many students on a certain unit, a student can have many trainers for different units.

dleroari's avatar

Then the relationship between trainer and student would be: Trainer hasMany() students. Students belongsToMany() Trainers.

Please or to participate in this conversation.