i am working on a Laravel 8 project and i have a bunch of categories that i selected in my multi select bar of my Form, and i want to return the suppliers in my database for each category i have selected so that i can display them in the next select bar of my Form,im using ajax for that but i don’ seem to figure out how to combine the suppliers of each category in one final result so i get to send it back to my view in json , can someone tell me what am i doing wrong and how to fix this please ? here is my controller
public function get_fournisseurs(Request $request){
try {
if($request->ajax()) {
$query = $request->get('selectednumbers');
if(empty($query)) {
return back()->withError("Désolé, une erreur de serveur s'est produite (requête vide)");
}
else {
$fournisseurs[] = new FourCats();
foreach ($query as $value) {
$fou[]=FourCats::join('fournisseurs','four_cat.four', '=', 'fournisseurs.id')
->where('four_cat.cat','=', $value)
->select('fournisseurs.id','fournisseurs.nomSociete','fournisseurs.id','fournisseurs.tel')
->get();
foreach($fou as $f) {
$fournisseurs = implode(array($f));
}
$fournisseurs = implode(array( $fournisseurs));
}
return json_encode(array('data'=>$fournisseurs));
}
}
} catch (Throwable $th) {
throw $th;
}
and here is my ajax method
$('#first-choice').change(function(){
if( $('#first-choice :selected').length > 0){
var selectednumbers = [];
$('#first-choice :selected').each(function(i, selected) {
selectednumbers[i] = $(selected).val();
});
console.log(selectednumbers);
$.ajax({
url: '{{ url('get_fournisseurs') }}',
method:'GET',
data: {selectednumbers: selectednumbers },
dataType: 'json',
success: function(dataResult){
var resultData = dataResult.data;
console.log(resultData);
$('#second-choice').empty();
$.each(JSON.parse(resultData), function(i,row){
$('#second-choice').append(new Option( row.id+'-'+row.nomSociete, row.id));
})
}
});
}
});
now this one works without errors except that the logic of my controller is wrong this code is showing me the suppliers of the last selected category even when i send 3 categories or more, i want the final result to combine the suppliers of all the selected categories not just the last one in the list, even with the double loop it isn’t working please help me fix my loop logic
2
Answers
I found what worked for me ^^ thank you for those who tried to help
My controller :
ajax methode :
Just delete or uncomment this line then it should work.
implode() makes a string but you need an array.
This is the reason that you get an conversion error.
And you define $fournisseurs=[]; twice. Just uncomment this.
Then do
you can also check the json response with
I’m not an Laravel expert but I think you don’t need that foreach loop everything from the database will be in the variable see: