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

hafiz_r's avatar

How to get two foreign key details from a table with same model?

Schema::create('appointments', function (Blueprint $table) {
            $table->increments('id')->onDelete('cascade');
            $table->integer('student_id')->unsigned()->nullable();
            $table->foreign('student_id', '35989_5913ebf64ed0b')->references('id')->on('students')->onDelete('cascade');
            $table->integer('counselor_id')->unsigned()->nullable();
            $table->foreign('counselor_id', '35989_5913ebf652b9b')->references('id')->on('counselors')->onDelete('cascade');
            $table->datetime('date')->nullable();
            $table->text('comments')->nullable();
            $table->unique(['counselor_id', 'date']);
            $table->unique('student_id');
            $table->timestamps();
        });

model

class Appointment extends Model
{
    public function counselor()
    {
        return $this->belongsTo(User::class, 'counselor_id');
    }

    public function student()
    {
        return $this->belongsTo(Student::class);
    }
}

controller

 $user = Auth::user();

        $appointments = Appointment::query()
            ->with(['student']) // eager load appointment's student
            ->where('counselor_id', $user->id) // filter by current user
            ->whereHas('student') // only appointments with students
            ->get();

        return view('appointedStudents')->with('appointments', $appointments);

I can get student details but i want to get counselor details too

0 likes
1 reply
tisuchi's avatar

@hafiz_r

You have relationships already. Just use counselor in with.

Try-

$user = Auth::user();

$appointments = Appointment::with(['student', 'counselor']) // eager load appointment's student and counselor
    ->where('counselor_id', $user->id) // filter by current user
    ->get();

return view('appointedStudents')->with('appointments', $appointments);
hafiz_r's avatar

thanks but when i login as student i want the counselor with whom i have the appointment with can i see that with this query?

Please or to participate in this conversation.