chabun's avatar

Filtering dropdown list by previous dropdown selected

Hello everyone,

In my laravel project, I have 2 dropdown lists in a form : Courses and Subjects; I'd like to have my Subjects dropdown list automatically filtered by what was selected in the Courses dropdown list before.

In my Subject model the relationship is like this,

public function courses()
    {
        return $this->belongsToMany(Course::class);
    }

And in my SubjectController,

public function getSubjects(Request $request)
    {
        $html = '';
        $subjects = Subject::whereHas('courses', function ($query) use($request){
           $query->where('course_id', $request->input('course_id'));
        })->get()->pluck('name', 'id');
        foreach($subjects as $subject){
            $html .= '<option value"' . $subject->id . '">' . $subject->name . '</option>';
        }

        return response()->json(['html' => $html]);
    }

And in my web.php, I've also added this line,

Route::get('subjects/get_by_course', 'SubjectController@getSubjects')->name('subjects.get_by_course');

And in the blade,

<div class="form-group">
     <label class="required" for="course_id">{{ trans('Course') }}</label>
          <select class="form-control select2" name="course_id" id="course_id">
              @foreach($courses as $id => $entry)
                    <option value="{{ $id }}" {{ old('course_id') == $id ? 'selected' : '' }}>{{ $entry }}</option>
              @endforeach
          </select>
</div>
<div class="form-group">
        <label for="subjects">{{ trans('Subjects') }}</label>
         <select class="form-control select2 multiple" name="subjects[]" id="subjects">
              <option value="">{{ trans('Please select) }}</option>
         </select>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        $("#course_id").change(function(){
            $.ajax({
                url: "{{ route('subjects.get_by_course') }}?course_id=" + $(this).val(),
                method: 'GET',
                success: function(data){
                    $("#subjects").html(data.html);
                }
            });
        });
    });

</script>

But when I tried it, nothing showed up in the subjects dropdown list. When I tried dd($subjects) with a specific course_id instead the $request->course_id, I have the result subjects that are ok. What did I miss?

0 likes
3 replies
chabun's avatar

@vdvcoder thank you for your reply. I've modified my codes following the link tutorial, but it's still not showing anything

Please or to participate in this conversation.