mardi 21 avril 2020

Dynamic Create $input in Laravel Controller to Insert data into table ( Error due to Foreach loop not working properly)

Respected Sir/Ma'am, I have different product and I want to create a dynamic $input in controller to save product information into database


Example

    $imput['name'] = $request->get('name');
    $imput['price'] = $request->get('price');
    $imput['description'] = $request->get('description');

To create above input dynamically in controller I try to use foreach loop and pass Input key and value from Frontend side


Example

    [["name", "biryani"], ["size", "full"], ["price", "200"], ["description", "chicken + rice"], ["url", 
    …],…]
    0: ["name", "biryani"]
    1: ["size", "full"]
    2: ["price", "200"]
    3: ["description", "chicken + rice"]
    4: ["url",…]
    5: ["modelName", "chickenBiryani"]

Code i write in controller

(where i do mistake , this code not working also please give answer which I mention in below code comment , Thank You)

  public function upload($productInfo)
    {
     $imput=[];
        foreach ($productInfo as $data) {
             // return $productInfo -- this return data
            // return $data -- this return throw error , why this happen
            foreach ($data as $val) {
            // return $val -- this return data
                if ($val[0] == 'modelName') {
                    $modelName = '\\App\\' . $val[1];
                } else {
                    $input[$val[0]] = $val[1];
                }
            }
        }
        $model = new $modelName;
        $model::create($imput);
        return response()->json(['msg' => 'Profile Image Upload Succeessfully']);
    }

Please help me sir i am new in Laravel



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire