Reputation: 65
I want when select one value from first dropdown to automatcly populate another dropdown based on first dropdown value.
My view:
<label for="category">Catégorie(s):</label>
{!! Form::select('category', $category,null, array('class' => 'form-
control')) !!}
<label for="brand">Marque:</label>
{!! Form::select('brand_name', $brand_name,null, array('class' => 'form-control')) !!}
My controller:
public function index()
{
$category = Category::pluck('categoryName', 'id');
$brand = Brand::pluck('brandName', 'id');
return view ( 'site.indexS',compact('brand','category') );
}
How to populate another dropdown? Any idea?
Upvotes: 0
Views: 3122
Reputation: 256
you can easily do it with a little bit of ajax and get method. May be you are trying to load brand depend on category lets roll :
Your controller:
public function index()
{
$category = Category::pluck('categoryName', 'id');
// no need to query brand here because we will load it depend on category
$brand = [];
return view ( 'site.indexS',compact('brand','category') );
}
// here we are adding another method in your controller which will return brand object depend on category id
public get_brand($categpry_id){
// hope your brand table contain category_id or any name as you wish which act as foreign key
$brands= Brand::where('category_id',$category_id)
->pluck('brandName','id');
return json_encode($brands);
}
Now in route we need to add this to hit this url :
Route::get('get-brand','YourControllerName@get_brand');
In view :
{{-- i am adding id for both dropdown --}}
Catégorie(s):
{!! Form::select('category', $category,null, array('id' => 'category_dropdown','class' => 'form-
control')) !!}
<label for="brand">Marque:</label>
{!! Form::select('brand_name', $brand_name,null, array('id' => 'brand_dropdown','class' => 'form-control')) !!}
now in our view file we need to use ajax, there is many other way i am preferring ajax here
<script type="text/javascript">
var url = "{{url('/')}}";
</script>
<script type="text/javascript">
$('#category_dropdown').on('change', function() {
$('#brand_dropdown').empty();
var id = $('#category_dropdown').val();
$('#brand_dropdown').html('<option selected="selected" value="">Loading...</option>');
var url = url + '/get-brand/'+id;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success:function(data) {
//console.log(data);
$('#brand_dropdown').html('<option selected="selected" value="">Select Brand</option>');
$.each(data, function(key, value) {
$('#brand_dropdown').append('<option value="'+key+'">'+value+'</option>');
});
}
});
});
</script>
Upvotes: 1