gouseferoz
1 week ago

with() and where() in eager Loading

Posted 1 week ago by gouseferoz

Hi,

I am trying to add relations and is confused with the implementation.

I have two tables, users and exams and i added some relations between two like the below code:

//User.pjp
public function exams()
    {
        return $this->hasMany(Exams::class);
    }
//Exams.php
public function user()
    {
        return $this->belongsTo(User::class);
    }

and trying to implement eager loading using the below code:

$exams = Exams::with('user')->get();
        $users = User::all();
        foreach($exams as $exam)
        {
            echo $exam->user;
        }

My requirement is , i want to select a particular exam from the Exams table based on the id but dont know how to implement it.

I need something like

public function showData($id)
    {
        $exams = Exams::with('user')->where('exam_id',$id)->get();
        $users = User::all();
        foreach($exams as $exam)
        {
            echo $exam->user;
        }
}

Can anyone help me how to do this?

Regards,

Please sign in or create an account to participate in this conversation.