0

I have a HTML code as below. Every time plus button click will create another row, of class="repeat" inclusive of all its inner elements. So basically each row will have input a,b,c,d,e and f.

<div class="row no-gutters mb-3 repeat">
    <div class="col-md-11">
         <input name="a[]" placeholder="a" class="mr-1" type="text">
         <input name="b[]" placeholder="b" class="mr-1" type="text">
         <input name="c[]" placeholder="c" class="mr-1" type="text">
         <input name="d[]" placeholder="d" class="mr-1" type="text">
         <input name="e[]" placeholder="e" class="mr-1" type="text">
         <input name="f[]" placeholder="f" type="text">
    </div>

    <div class="col-md-1 text-center">    
        <button class="btn btn-outline-success btn-sm add-more" type="button"><i class="fa fa-plus"></i></button>    
    </div>
</div>

My code in PHP looks like this (Using Laravel framework):

foreach($request->a as $a){
    foreach($request->b as $b){    
        foreach($request->c as $c){        
            foreach($request->d as $d){            
                foreach($request->e as $e){                
                    foreach($request->f as $f){                    
                        $data = [                        
                            'a' => $a, 'b' => $b, 'c' => $c, 'd' => $d, 'e' => $e, 'f' => $f                        
                        ];
                        Abc::create([$data]);                   
                    }                
                }            
            }        
        }    
    }
}

All I need is a suggestion to improve the above PHP code. Thanks in advance. :)

1
  • try using a json data type in laravel Commented Sep 24, 2019 at 2:51

1 Answer 1

1

Actually the foreach approach was wrong. We can add one more input element as hidden element as below to use as reference:

<input name="id[]" type="hidden">

Than in PHP we can do like this:

for($s = 0; $s < count($request->id); $s++){
    Abc::create([
        'a' => $request->a[$s],
        'b' => $request->b[$s],
        'c' => $request->c[$s],
        'd' => $request->d[$s],
        'e' => $request->e[$s],
        'f' => $request->f[$s]
    ]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.