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

_chris's avatar

Eloquent query help

I am working on a site which includes a number of quizzes. A user can preform a quiz which is saved to an assessment. I have the following models:

class User
{
    public function assessments()
    {
        return $this->hasMany(Assessment::class);
    }
}

class Quiz
{
    public function assessments()
    {
        return $this->hasMany(Assessment::class);
    }
}

class Assessment
{
public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function quiz()
    {
        return $this->belongsTo(Quiz::class);
    }
}

To get a list of all the current authenticated user's assessments I am currently doing the following:

$quiz = Quiz::where('name', 'my quiz')->firstOrFail();
$assessments = Auth::user()->assessments()->where('quiz_id', $quiz->id)->get();

I am then passing both the quiz and the assessments to the view.

return view('quiz')->with('quiz', $quiz)->with('assessments', $assessments);

I'd like to know if there is a better way of doing this to reduce it to one sql query and also eager load the quiz into the results. Something like:

$assessments = Auth::user()->assessments()->with('quiz')->where('name', 'my quiz')->get();

Any thoughts?

0 likes
2 replies
flyingearl's avatar

Hi,

I think you may be able to do this by constraining eager load. I've added the link to Laravel's documentation if you want further reading but I think it'll look something like this:

Auth::user()->assessments->with(['quiz' => function($query) {
    $query->where('name', 'my quiz');
}])->get();

I hope that helps.

_chris's avatar

That works, thanks. Just needed to change :

$query->where('name', 'my quiz');

to:

$query->where('name', '=', 'my quiz');

Please or to participate in this conversation.