deepu07
273
9
Laravel

Get all the records by using explode

Posted 4 months ago by deepu07

Hi Guys Can anyone help me out (URL: http://localhost/getStudents/4:5:6:7) Even 4,5,6,7 records existed in database but not getting all the records and displaying only last record. How to display all the existed records in output? Thanks in advance

```public function getStudents($ids)
{   
    if(!$ids) 
        return "Please enter a valid student id";

    $studentIds = explode(':', $ids);

    $data = [];

    // fill output with blank data
    foreach ($studentIds as $studentId) {
        $data[$studentId] = [];
    }
    $students = Student::where('id', $studentId)->get();

    if(!$students)
        return "No Students are found with this . '$studentId' .";
    
    foreach ($students as $student) {
        $studentData=[];
        // $data[$studentId] = [];

        $studentData['roll_nuber'] = $student->roll_number;
        $studentData['first_name'] = $student->first_name;
        $studentData['last_name'] = $student->last_name;
        $studentData['gender'] = $student->gender;
        $studentData['graduated_year'] = $student->graduated_year;
        array_push($data, $studentData);
    }
    return response(['success' => true, 'data' => $data], 200);
}```

output

    "success": true,
    "data": {
        "4": [],
        "5": [],
        "6": [],
        "7": [],
        "8": {
            "roll_nuber": "[email protected]",
            "first_name": "Randy",
            "last_name": "Daugherty",
            "gender": "Female",
            "graduated_year": "2000-01-01"
        }
    }
}```




***expected***
```{
    "success": true,
    "data": {
       "4": {
            "roll_nuber": "[email protected]",
            "first_name": "Ran",
            "last_name": "Daugherty",
            "gender": "Female",
            "graduated_year": "2003-01-01"
        },
        "5": {
            "roll_nuber": "[email protected]",
            "first_name": "Rand",
            "last_name": "Daugh",
            "gender": "Female",
            "graduated_year": "2004-01-01"
        },
        "6": {
            "roll_nuber": "[email protected]",
            "first_name": "Randz",
            "last_name": "Daughe",
            "gender": "Female",
            "graduated_year": "2007-01-01"
        },
       "7": {
            "roll_nuber": "[email protected]",
            "first_name": "Randyy",
            "last_name": "Daughert",
            "gender": "male",
            "graduated_year": "2001-01-01"
        },
        "8": {
            "roll_nuber": "[email protected]",
            "first_name": "Randyyy",
            "last_name": "Daugherty",
            "gender": "male",
            "graduated_year": "2010-01-01"
        }
    }
}```

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.