skip to Main Content

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


  1. Chosen as BEST ANSWER

    I found what worked for me ^^ thank you for those who tried to help

    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=FourCats::join('fournisseurs','four_cat.four', '=', 'fournisseurs.id')
                        ->whereIn('four_cat.cat',$query)
                        ->select('fournisseurs.id','fournisseurs.nomSociete','fournisseurs.id','fournisseurs.tel')
                        ->distinct()
                        ->get();
    
                  return json_encode(array('data'=>$fournisseurs));
                   // return response()->json($fournisseurs);
    
                }
            }
    
        } catch (Throwable $th) {
            throw $th;
        }
    }
    

    ajax methode :

    $('#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;
                        $('#second-choice').empty();
                        $.each(resultData, function(i,row){
                            $('#second-choice').append(new Option( row.id+'-'+row.nomSociete, row.id));
                        })
                    }
                });
            }
        });
    

  2. 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.

    $fournisseurs = implode($fournisseurs);
    

    And you define $fournisseurs=[]; twice. Just uncomment this.

    Then do

    return response()->json($fournisseurs);
    

    you can also check the json response with

    $data = response()->json($fournisseurs);
    print_r($data)
    

    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:

    $fournisseurs = DB::table('yourTableName') -
      > join('fournisseurs', 'four_cat.four', '=', 'fournisseurs.id') -
      > select('fournisseurs.id', 'fournisseurs.nomSociete', 'fournisseurs.id', 'fournisseurs.tel') -
      > where('four_cat.cat', '=', $value) -
      > get();
      
    return json_encode(array($fournisseurs));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search