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

derrickrozay's avatar

Querying information from multiple tables based on the user currently logged in

I am using Laravel 5.6 and trying to query information from the grading_info table but I also want to return the students name and other info from the student_info table. I only want to return records in the grading_info table that are related to the currently logged in teacher. Currently its returning information for all teachers. I know I can add a where clause but I am trying to learn eloquent and was wondering if there was any way to accomplish this?

Teachers and students can have many enteries in the grading_info table and any teacher can grade any student.

I would like to return something like this

    {
        gradeID,
        gradeDate,
        gradeInfo
        .....
        student: {
            studentName,
            studentPhoneNumber,
            studentEmail
            ......
        }
    }

users table (only stores teachers, not student)

  • id

teacher_info

  • teacherID (linked to id from users table)

student_info

  • id (auto increment. not relation to the users table)

grading_info

  • studentID (linked to id from student_info)
  • teacherID (linked to id from users)

User model

public function grades(){
    return $this->hasMany(GradingInfo::class, 'studentID');
}

GradingInfo model

public function teacher(){
   return $this->belongsTo(User::class, 'id', 'teacherID');
}

public function student() {
    return $this->belongsTo(StudentInfo::class, 'studentID', 'id');
}

StudentInfo model

public function grades() {
    return $this->hasMany(SessionInfo::class, 'studentID', 'id');
}

TeacherInfo model

   // Nothing in here. 

TeacherController

public function getGrades(Request $request)
{
    $user       = Auth::user(); // This is the teacher
    $grades  = $user->with('sessions.student')->orderBy('created_at', 'DESC')->get();
   return response()->json(['sessions' => $sessions], 200);
    }
0 likes
1 reply
NickVahalik's avatar

There are a few ways to slice it. One thing you could do is add a scope to your GradingInfo class that takes a Teacher as a param and then limits the results based on that:

public function scopeOnlyTeacher(User $teacher)
{
    $query->where('teacherId', $teacher->id);
}

The idea here is that you can then do:

GradingInfo::onlyTeacher($user); // only returns items related to the teacher

Then, if the current logged in user is a teacher:

tap($gradingInfoQuery)->when(/* user is a teacher */, function ($query) {
    $query->onlyTeacher(Auth()::user());
})

Please or to participate in this conversation.