Search code examples
phpjsonlaravelpostmannested-loops

one request to apply many changes in the DB


i have alot of records that needs to be edited in one request, so i went for POST request to try to edit the data in my controller like this :

foreach ($attr as $key){
        foreach ($key->item as $attribute) {
            if ($attribute['action'] == 'store') {
                $insert_array = [
                    'subject_quiz_id' => $key->subject_quiz_id,
                    'registration_record_id' => $attribute->registration_record_id,
                    'mark' => $attribute->mark
                ];

            }
        } }

and this is my postman :

{
"subject_quiz_id": "7",
"item": [{
        "action": "store",
        "registration_record_id": "7",
        "mark": "3"
    },
    {
        "action": "store",
        "registration_record_id": "7",
        "mark": "3"
    }]}

but it simply keep pushing this error:

    "message": "Trying to get property 'item' of non-object",
"exception": "ErrorException",

Solution

  • $insert_array = [];
    foreach ($request->all() as $item) {
                if (is_array($item)) {
                    foreach ($item as $value) {
                        if (isset($value['action'], $value['registration_record_id'], $value['mark']) && $value['action'] === 'store') {
                            $insert_array[] = [
                                'subject_quiz_id' => $request->subject_quiz_id,
                                'registration_record_id' => $value['registration_record_id'],
                                'mark' => $value['mark'],
                            ];
                        }
                    }
                }
            }
    dd($insert_array);