1

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());

        }
    }
123t
  • 77
  • 1
  • 10
  • Saving multiple items like this in a single column is probably a sign of bad database design - https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – Nigel Ren Apr 16 '20 at 06:29

1 Answers1

1

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.

Brian Lee
  • 17,904
  • 3
  • 41
  • 52