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

satyanarayana's avatar

Many to Many Relationship with 2 pivot table data search


Hi i have 5 tables

Skills id name 1 PHP 2 Laravel

Qualifications id name 1 MBA 2 Graduate 3 Post Graduate

students id name 1 John 2 Smith

2 pivot tables

student_skills student_id skill_id 1 1 1 2 2 1

student_qualifications tutor_id qualification_id 1 2 1 2 2 2

In frontend the user can select multiple qualifications(checkboxes) and skills(checkboxes) according to the options selected we need to display the data.

Thanks.

0 likes
1 reply
tykus's avatar

Assuming you want to get all students where any of the qualifications or skills criteria are met:

    $skills = $request->skills;
    $qualifications = $request->qualifications;

    return App\Student::whereHas('qualifications', function ($q) use ($qualifications) {
        $q->whereIn('qualification_id', $qualifications);
    })->orWhereHas('skills', function ($q) use ($skills) { 
        $q->whereIn('skill_id', $skills);
    })->get();

You will be receiving an array each of qualifications and skills from the form. This assumes you have created the belongsToMany relationships on the App\Student model for both qualifications and skills.

If you wanted to constrain by any selected qualification and any selected skill, change out orWhereHas with whereHas

Please or to participate in this conversation.