skip to Main Content

Can anyone please help me for setting the correct foreach loop for sending multiple input values to the database (MySQL), Whenever I execute this code in postman only one entry gets uploaded in the database. I want to send multiple “user_id” at once.

$input = json_decode(file_get_contents('php://input', true));

foreach($input->users as $user) {
    $groupId = $user->group_id;

    $groups = Group::where("group_id", $groupId)
        ->get()->first();

    foreach($input->users as $user2) {

        $groupMembers = new GroupMembers();

        $userId = $user2->user_id;
        $groupMembers->group_id = $groups->group_id;

        $users1 = Users::where("user_id", $userId)
            ->get()->first();

        $groupMembers->member_user_id = $users1->user_id;
        $response = json_decode($groupMembers, true);

        $save = $groupMembers->save();

Input json:

{
    "users" : [{
        "group_id" : "1",
        "user_id" : ["2", "3", "4"]
}]}

2

Answers


  1. Try this you are iterating through users it should be user_id

    foreach($input->users['user_id'] as $user) {
    
    Login or Signup to reply.
  2. Try the following

    foreach($input->users as $user) {
              $groupId = $user->group_id;
    
              $groups = Group::where("group_id", $groupId)
                  ->get()->first();
    
              foreach($user->user_id as $userId) {
    
                  $groupMembers = new GroupMembers();
    
                  $groupMembers->group_id = $groups->group_id;
    
                  $users1 = Users::where("user_id", $userId)
                      ->get()->first();
    
                  $groupMembers->member_user_id = $userId;
                  $response = json_decode($groupMembers, true);
    
                  $save = $groupMembers->save();}
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search