Laravel Insert multiple records from one form

删除回忆录丶 提交于 2021-01-28 11:43:49

问题


I'm working on a task to add extra to items, I have a select field to add item_id and save it to extras table in the database.

I'm trying to add more than 1 items to save my time instead of adding same extra to another items.

I'll share the current code work for one item ONLY :

View:

 {!! Form::select('food_id', $food, null, ['class' => 'select2 form-control']) !!}

my try do make it insert multiple ids:

{!! Form::select('food_id[]', $food, null, ['class' => 'select2 form-control', 'multiple'=>'multiple']) !!}

controller :

public function create()
{
    $this->foodRepository->pushCriteria(new FoodsOfUserCriteria(auth()->id()));
    $food = $this->foodRepository->groupedByRestaurants();
    $extraGroup = $this->extraGroupRepository->pluck('name', 'id');

    $hasCustomField = in_array($this->extraRepository->model(), setting('custom_field_models', []));
    if ($hasCustomField) {
        $customFields = $this->customFieldRepository->findByField('custom_field_model', $this->extraRepository->model());
        $html = generateCustomField($customFields);
    }
    return view('extras.create')->with("customFields", isset($html) ? $html : false)->with("food", $food)->with("extraGroup", $extraGroup);
}

Error shown :

ErrorException (E_NOTICE) Array to string conversion

Error Highlight :

    foreach ($segments as $segment) {
        $result .= (array_shift($replace) ?? $search).$segment;
    }

'food_id' => 'integer'

if I print_r($request->all()); it show me this result :

Array ( [_token] => p1oO45NAnBfqvMHm [name] => 23 => [price] => 9 [food_id] => Array ( [0] => 33 [1] => 34 ) [extra_group_id] => 4 ) 

I hope I explain it clearly, waiting for a help :) Thanks


回答1:


you can try this something like this

 if(count($request->food_id) > 0){
        for($i = 0; $i < count($request->food_id); $i++){
            $object = new Model();
            $object->food_id = $request->food_id[$i];
            $object->save();
        } 
    }
    



回答2:


Thank you for all personnel trying to help me, I would like to share the solution I made to make it done :

     $input = $request->all();
     $food_ids = $input['food_id'];
     foreach($food_ids as $food_id) {
       $input['food_id'] = $food_id;
       ...
       ...

       $extra = $this->extraRepository->create($input);
     }


来源:https://stackoverflow.com/questions/62616115/laravel-insert-multiple-records-from-one-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!