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

Randy_Johnson's avatar

DB Querying! dedrater ma I

Hi, I am currently working on a project where I am having trouble just linking somethings together through the relationships. Now, as I can imagine I have done most things correctly and I am just stuck on the final hurdle. But we shall soon find out.

I just want to grab the students who are currently linked to the teacher that is being used, the teacher is selected from a drop down box, giving the $this->teacherId.

I have three tables, teacher, student, attendance, attendance linking the teacher and student together.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Attendance extends Model
{
    use HasFactory;

    public function teacher()
    {
        return $this->hasOne(Teacher::class, 'teacher_id', 'id');
    }

    public function student()
    {
        return $this->hasOne(Student::class, 'student_id', 'id');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'surname',
    ];

    public function attendance()
    {
        return $this->hasMany(Attendance::class, 'student_id');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Teacher extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'surname',
    ];

    public function attendance()
    {
        return $this->hasMany(Attendance::class, 'teacher_id');
    }
}
$this->students = Attendance::where('teacher_id', '=', $this->teacherId)->get();
        
        dd($this->students);
0 likes
2 replies
SilenceBringer's avatar
Level 55

@randy_johnson try something like

$this->students = Student::whereHas('attendance', function ($query) {
    $query->where('teacher_id', $this->teacherId);
})
    ->get();
Randy_Johnson's avatar

Perfect. Do you have any good resources where I can learn more of this stuff, because my knowledge is really lacking.

Please or to participate in this conversation.