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

Alphal's avatar

Can't figure out how to display subjects of a specific year with dropdown

I am trying to figure out how to get all the subjects of a specific year with ajax, jquery in Laravel. I have three tables:

years: id, name subjects: id, name year_subject: id, year_id , subject_id

Here is the function in controller

public function get_subjects($id) {$sub = YearSubject::where("year_id", $id)->pluck("subject_id"); $subjects=Subject::where('$id',$sub)->pluck('name','id'); foreach($sub as $s)

            {
              $subjects= Subject::where('$id',$s)->pluck('name','id');
           }
    return json_encode($subjects);
        }

Here is the script

$(document).ready(function () { $('#grade').on('change', function () { var gradeID = $(this).val(); $('#subject').empty(); if (gradeID) { $.ajax({ url: '{{url('get_subjects')}}' + '/' + gradeID, type: "GET", dataType: "json", success: function (data) { $.each(data, function (key, value) { $('#subject').append('' + value + ''); }); } }); } else { $('#subject').empty(); } }); });

The view

Choose Year @foreach($grades as $grade) {{$grade->name}} @endforeach Choose Subject

Route:

Route::get('get_subjects/{id}', 'SubjectController@get_subjects')->name('get_subjects')

I guess the error is at the controller. Can't figure out how to push values at $subjects.

0 likes
2 replies
Tray2's avatar

Please wrap the code block in three ` (backtics) to make it readable.

Cronix's avatar

First thing I'd do is add some relationships to the Year and Subject models. It would be a belongsToMany() in each case, and you don't need a YearSubject model' at all for the pivot table. You do need the pivot table, but it should be calledsubject_year` (should be alphabetical order of the singular form of each table it's referencing).

Then you could just do Year::with('subject')->find($year_id); and get everything you need. The year with all subjects for it.

https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

This also won't work with php:

Subject::where('$id',$s)
// or
Subject::where('$id',$sub)

where you have a variable, $id, in single quotes. That literally is the string '$id' and not the variables value.

Please or to participate in this conversation.