Skip to content
Advertisement

How to solve Array to string conversion Error?

here user can select multiple foods. i want to save those food items to the database. I have column named “food” in the database i want to save all those selected food items in this column. just like this enter image description here . Right now I am getting this error Array to string conversion. If Anyone knows how to fix it please tell me.

                 state = {
                  food : []
                 }
                       <Form.Item {...formItemLayout} label="Select Foods">
                            {getFieldDecorator('food', {
                                rules: [
                                    {
                                        required: true,
                                        message: 'Please select Food!',
                                    },
                                ],

                            })(<Select
                                mode="multiple"
                                placeholder="Select"
                                style={{ width: 350 }}
                                defaultValue={"Select"}
                                onChange={(e) => { this.setState({ food: e }) }}
                            >
                                <Option value="Pan Cakes">Pan Cakes</Option>
                                <Option value="fried Rice">fried Rice</Option>
                                <Option value="Vegetable Soup">Vegetable Soup</Option>
                                <Option value="Pizza">Pizza</Option>
                                <Option value="crab">crab</Option>
                                <Option value="burger">burger</Option>
                            </Select>
                            )}

                        </Form.Item>

 public function saveFoods(Request $request){
        try {
          $jsonData = json_decode($request->getContent());
          $saveDetails = new Foodmodel();
          $saveDetails->food = $jsonData->food;
          $saveDetails->save();
        } catch (Exception $e) {
            ErrorHandler::logError($e, 'Error');
            return $this->jsonResponse('error', $e->getMessage());

        }
    }

Advertisement

Answer

If you’re simply trying to save the food list as a comma separated string:

 $saveDetails->food = implode(',', $jsonData->food);

Or better yet, add the food attribute to your models $casts property to automatically handle the conversion between an array and string.

See the docs here for casting details.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement