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

eggplantSword's avatar

Filter items in collection depending on a item column.

I'm trying to get all the sections and filter the questions inside each section using the column user_id that's for the questions. The tables go like this

 Schema::create('survey_sections', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->longText('description');
            $table->timestamps();
        });
Schema::create('survey_questions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('question');
            $table->string('instruction')->nullable();
            $table->integer('user_id')->unsigned();
            $table->integer('survey_section_id')->unsigned();
            $table->integer('response_type_id')->unsigned();
            $table->boolean('optional');
            $table->integer('num')->nullable();
            $table->integer('rank')->nullable();
            $table->boolean('show_text')->nullable();
            $table->timestamps();
            $table->foreign('survey_section_id')->references('id')->on('survey_sections');
            $table->foreign('response_type_id')->references('id')->on('response_types');
            $table->foreign('user_id')->references('id')->on('users');
        });

This is what I've tried

$user = auth()->user()->user_type_id;
if ($user === 1) {
    $surveySection = SurveySection::with('questions')->get();
} else if ($user === 2 || $user === 3) {
    $surveySection = SurveySection::with('questions')
        ->whereHas('questions', function ($query) {
            $query->where('user_id', auth()->user()->id);
        })->get();
}
dd(json_encode($surveySection));

(I'm logged in as user type = 2)

However the output is not what I wanted, it shows me one section where the user has added questions but it shows me all the questions, I want it to show all the sections and when a section is selected it will only show the questions the logged in user has created for that section.

The logic is because this is a survey website for a school, if multiple people are adding questions to the same section when selected for a survey everyone's questions will be shown and it would be a mess to then go one by one and delete the questions that don't belong to the user, I want only the questions that the person created to show up.

0 likes
1 reply
Sti3bas's avatar
SurveySection::with('questions', function($query) {
   $query->where('user_id', auth()->user()->id);
})->get();

Please or to participate in this conversation.