I have 3 selection fields, sites
, areas
, devices
I need to filter the devices list according to what was selected in sites
and areas
so the list will include only devices from that site and that area only.
Made it work only with areas
but getting error 500 when trying to pass another variable for sites
in JS
Route:
Route::get('devices/workarea/{work_area_id?}/{site_id?}','DevicesController@getDevicesByArea')->name('devices.byArea');
Controller:
public function getDevicesByArea($work_area_code = NULL) {
$devices = array();
if($work_area_code != NULL){
$workArea = WorkArea::find($work_area_code);
if($workArea) {
$devices = Device::selectRaw('id, CONCAT(device_alias) as work_device')
->where('belongs_to_work_area_id',$work_area_code)
->get()
->pluck('work_device', 'id');
}
}
return json_encode($devices);
}
JQuery:
$(document).ready(function () {
$("#area_id").on('change', function(){
var area_id = this.value;
var site_id = $('#site_id').val();
console.log(area_id)
console.log(site_id)
var deviceUrl = "{{ route('admin.devices.byArea') }}/" + area_id;
$.ajax({
url: deviceUrl,
success: function(result){
var html = '<option value="">Please select</option>';
result = jQuery.parseJSON(result);
console.log(result);
for(var key in result) {
html += '<option value="'+key+'">'+result[key]+'</option>';
}
$("#device_id").html(html);
$('#device_id').val('');
}
});
});
});
How to correctly send the second needed parameter site_id
to controller and filter the devices at the same time by both area_id
and site_id
?
2
Answers
You need to add the parameter to the method. Update your query as needed, and also sanitize the input value from both values you are getting in the url.
jQuery
You need to add the parameter to the url, to be able to be send to the method.
Route
Code in Controller
jQuery Code