ramtawker ramtawker - 5 months ago 179
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

<?php

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

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

protected $fillable = ["name"];
}


in model Subcategory

<?php

namespace App;



use Illuminate\Database\Eloquent\Model;

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

}


in View :

<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<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>-->
</head>

<body>
<div class="container">

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

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

</select>


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

<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#category').on('change', function(e){
console.log(e);

var category_id = e.target.value;

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

$('#subcategory').empty();

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

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

});
});
});
</script>


{{Form::close()}}
</div>



</body>

</html>

Answer

reference your Subcategory model in the controller

use App\Http\Controllers\Subcategory
Comments