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

Zoul's avatar
Level 5

Subcategories fields are not showing.

Hey folks,

I have two tables, one  is Category with:
 Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category_name');
            $table->timestamps();
        });
And subcategories table with:
 Schema::create('subcategories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('category_id');
            $table->string('subcategory_name');
            $table->timestamps();
        });

=in Category model:
 public function subcategories(){
        return $this->hasMany(Subcategory::class,'category_id');
    }
= in Subcategory model:
  public function category(){
        return $this->belongsTo(Category::class,'category_id');
    }

=in controller this method send all categories to template:
public function createProduct(){
        $category = Category::selection()->get();
        return view('admin.product.create',compact('category'));
    }

=with this method i get the category id and associate it to its subcategory and re-send it back 
to template 
public function getSubCat($id){
       $cat = Category::selection()->find($id);
      $subcat = $cat->subcategories;

        return response()->json($subcat );
    }

= in tempate, the categories are already showing up 
 <select class="form-control select2" data-placeholder="Choose category" name="category">
                                        <option label="Choose Category"></option>
                                        @foreach($category as $row)
                                            <option value="{{ $row->id }}">{{ $row->category_name }}</option>
                                        @endforeach
                   </select>
------
	<select class="form-control select2" data-placeholder="Choose subcategory" name="subcategory_name">
                                        <option value=""></option>
		</select>

= jquery and ajax method
<script type="text/javascript">

        $(function() {
            $('select[name="category"]').on('change', function () {
                var countryID = $(this).val();

                if (countryID) {
                    $.get('/subcategory/' + countryID, function(data) {
                        $('select[name="subcategory_name"]').empty();

                        $.each(data,function(key, value) {
                            $('select[name="subcategory_name"]').append('<option value="'+ value.id + '">' + value.subcategory_name + '</option>');
                        });
                    }, 'json');
                } else {
                    $('select[name="subcategory_name"]').empty();
                }
            });
        });
  </script>

I have tried many different methods but its still not working, i really appreciate your help !
0 likes
10 replies
bobbybouwmann's avatar

So it seems your javascript is not working correctly. Do you see any errors in the debuggers console in your browser?

Have you tried adding console.log or alert to your script to see where it gets and where it doesn't get?

s4muel's avatar

is your route correct? you call /getStates/ in the ajax, and the method to get subcategories is named getSubCat($id)

something like this

Route::get('/getStates/{id}', 'YourControllerWithGetSubCatMethod@getSubCat');
Zoul's avatar
Level 5

Hey @bobbybouwmann , thank you so much for your support !

I found this errors in console

rickshaw.min.js:1 Uncaught Rickshaw.Graph needs a reference to an element initialize @ rickshaw.min.js:1 Rickshaw.Graph @ rickshaw.min.js:1 (anonymous) @ dashboard.js:23 fire @ jquery.js:3099 fireWith @ jquery.js:3211 ready @ jquery.js:3417 completed @ jquery.js:3433 jquery.js:8630 GET http://localhost/subcategory/2 404 (Not Found) send @ jquery.js:8630 ajax @ jquery.js:8166 jQuery. @ jquery.js:8311 (anonymous) @ create:601 dispatch @ jquery.js:4435 elemData.handle @ jquery.js:4121 ListPicker._handleMouseUp jquery.js:8630 GET http://localhost/subcategory/4 404 (Not Found)

Zoul's avatar
Level 5

Hey @s4muel ,

thanks a lot for you help ! It was getSubCat too,, but now i changed it to be more consistence, this is my getSubCat($id) method public function getSubCat($id){ $cat = Category::selection()->find($id); $subcat = $cat->subcategories;

    return response()->json($subcat);
}
bobbybouwmann's avatar

@zool So in your developer's console on the network tab you can see a successful API call?

Zoul's avatar
Level 5

Hey @bobbybouwmann , thanks for your help !,

I see 404 error, that it could not find the category id:

Request URL: http://localhost/subcategory/1 Request Method: GET Status Code: 404 Not Found Remote Address: [::1]:80 Referrer Policy: strict-origin-when-cross-origin

in my method getSubCat($id), i check the subcategory variable before sending it to template and i could successfully returned the subcategories related to category id coming from the template,

I even change the ajax method method to this one but still the same:

   $('select[name="category"]').on('change',function(){
            var category_id = $(this).val();
            if (category_id) {

                $.ajax({
                    url: "/subcategory/" + category_id ,
                    type:"GET",
                    dataType:"json",
                    success:function(data) {
                        if(data){
                            console.log(data);
                            var d = $('select[name="subcategory_name"]').empty();
                            $.each(data, function(key, value){
                                $('#subcategory_name').append('<option value="'+ value.id + '">' + value.subcategory_name + '</option>');
                            });
                        }else{
                            alert('No Data Found');
                        }

                    },
                });

            }
        });
bobbybouwmann's avatar
Level 88

Well, it seems that either the URL is not registered correctly as a route or you. You can run php artisan route:list and see if that URL actually exist or you can check your route files of course.

Zoul's avatar
Level 5

Hey @bobbybouwmann , Its working now. after checking the route ,php artisan route:list, found that i grouped all admins url with admin prefix, that i completely forgot to put it in ajax url. and i had to add slash as well. to make it work, url: "{{url('/admin/subcategory/')}}/" + category_id,

Thank you so much and the others for your great help !

Please or to participate in this conversation.