Search code examples
jsonlaravelapiresponse

get rid of numbers in json response (LARAVEL 8)


my function in a controller is here below

public function getStudentsinGrade($grade, $school_id){
       $students =  Student::where('school_id', $school_id)->get();
           $this -> grade = $grade;
       $gradeStudent= $students->filter(function($value,$key){
            return $value->grade == $this->grade;
       });
       if(count($gradeStudent) > 0){
        return  response()->json($gradeStudent);
       }
       else{
        return  response('No Registered Student');
       }
    }

the response I am getting is here below

*{
    "2": <---this number here is the problem and it appeared when get API response
{
        "id": 14,
        "student_name": "Polly Grain",
        "gender": "Female",
        "stream_id": 1,
        "school_id": 1,
        "final_year_id": 2,
        "grade": "Form Four"
    },
    "3": {
        "id": 15,
        "student_name": "Polly Grain",
        "gender": "Male",
        "stream_id": 3,
        "school_id": 1,
        "final_year_id": 2,
        "grade": "Form Four"}
}*

and the response I want to get is the one below

[ { "id": 1, "student_name": "sae sddat", "gender": "male", "stream_id": 2, "school_id": 10, "final_year_id": 12, "grade": "Form One" }, { "id": 1, "student_name": "sae sddat", "gender": "male", "stream_id": 2, "school_id": 10, "final_year_id": 12, "grade": "Form One" }, { "id": 1, "student_name": "sae sddat", "gender": "male", "stream_id": 2, "school_id": 10, "final_year_id": 12, "grade": "Form One" } ]


Solution

  • To fix this, first convert your collection to an array, then use the array_values() function to get rid of those annoying array keys that are bothering you. After that, convert back to a collection and pass it as a json response. IN CODE:

    public function getStudentsinGrade($grade, $school_id){
           $students =  Student::where('school_id', $school_id)->get();
               $this -> grade = $grade;
           $gradeStudent= $students->filter(function($value,$key){
                return $value->grade == $this->grade;
           });
           if(count($gradeStudent) > 0){
           $gradeStudent = collect(array_values($gradeStudent->toArray()));
          
            return  response()->json($gradeStudent);
           }
           else{
            return  response('No Registered Student');
           }
        }
    

    Now this will give you the desired result like this:

    {
            "id": 14,
            "student_name": "Polly Grain",
            "gender": "Female",
            "stream_id": 1,
            "school_id": 1,
            "final_year_id": 2,
            "grade": "Form Four"
        },
    {
            "id": 15,
            "student_name": "Polly Grain",
            "gender": "Male",
            "stream_id": 3,
            "school_id": 1,
            "final_year_id": 2,
            "grade": "Form Four"}
    }