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?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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 !
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.
Please or to participate in this conversation.