ramtawker ramtawker - 1 year ago 316
jQuery Question

dependent dropdown in laravel

i need a dependent dropdown in my laravel project, so i was trying with the below code which gives me 500 internal server error. in the first select box the values are displayed from the database but when i select one, the second select box does not display any value.

in the routes

Route::get('/', function () {
$categories = Category::all();

return view('welcome')->with('categories', $categories);

Route::get('ajax-subcat/{id}', 'Controller@ajaxcall');

in my controller


namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

class Controller extends BaseController
//use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

public function ajaxcall($id){
$subcategories = Subcategory::where('category_id', '=', $id)->get();
return Response::json($subcategories);

in model Category

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model

protected $fillable = ["name"];

in model Subcategory


namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
protected $fillable = ["name", "category_id" ];


in View :

<!DOCTYPE html>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>-->

<div class="container">

{{Form::open(array('url'=>' ', 'files'=>true))}}
<select class="form-control input-sm" name="category" id="category">

@foreach ($categories as $category)
<option value="{{$category->id}}"> {{$category->name}} </option>


<div class="form-group">
<select class="form-control input-sm" name="subcategory" id="subcategory">
<option value=" "></option>

headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
$('#category').on('change', function(e){

var category_id = e.target.value;

$.get('ajax-subcat/' + category_id, function(data){


$.each(data, function(index, subcatObj){

$('#subcategory').append('<option value ="'+ subcatObj.id +'">'+subcatObj.name+'</option>');





Answer Source

reference your Subcategory model in the controller

use App\Http\Controllers\Subcategory
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download