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

kpopdz's avatar

laravel query

hello guys i hope u fine in my project laravel have 4 table user teacher student class user has relation one to one with student and teacher the table student anq teacher has relation with table class i want find users (teacher,student) that are teaching and studying in same class

0 likes
4 replies
kevinbui's avatar

You can set up many to many relationships between a User and a Class using the students and teachers tables as intermediary.

class Class extends Model
{
    public function studentUsers()
    {
        return $this->belongsToMany(User::class, 'students', 'user_id', 'class_id');
    }

    public function teacherUsers()
    {
        return $this->belongsToMany(User::class, 'teachers', 'user_id', 'class_id');
    }
}

Then to get all users in the same class:

return $class->studentUsers->merge($class->teacherUsers);

That might solve your problem. But I don't particularly like this design. What about using this package to assign users with teacher and student roles?

kpopdz's avatar

@kevinbui .-. i have colmun role in table users u want only relation between users and class ?

kpopdz's avatar

@kevinbui where we put this line return $class->studentUsers->merge($class->teacherUsers);

kevinbui's avatar

@kpopdz That's the code to get all users in a class. You can put that in a public method:

class Class extends Model
{
    public function getUsers()
    {
        return $class->studentUsers->merge($class->teacherUsers);
    }
}

Please or to participate in this conversation.