Laravel add dynamic input fields

2019-08-01 07:35发布

I want to insert dynamic fields into DB. I'm using the following code but it does not work as I expect.

<html>
<input id="reporting" type="text" value="salman" name="reporting[]">    
<input id="reporting" type="text" value="ankur" name="reporting[]">    
</html>

<?php

 $report = Input::get('reporting');

 for($i=0; $i<=count($report);$i++)
        {
            $news = new Reporting();
            $news->user_id = 1;
            $news->reporting = $report;
            $news->save();
        }
?>

expected result:

user_id || reporting
1           Salman
1           Ankur  

Can you guys please help me to fix this.

2条回答
神经病院院长
2楼-- · 2019-08-01 08:36

You could map the collection and create a new report while storing value of reports the way you want:

<html>
<body>
@if(session('success'))
<div class="alert alert-success">
    {{ session('success') }}
</div>
@endif
<form action="/" method="post">
  {{csrf_field()}}
  <input id="reporting" type="text" value="salman" name="reporting[]">    
  <input id="reporting" type="text" value="ankur" name="reporting[]">  
  <button type ="submit"> Send </button>
</form>  
</body>
</html>

Catch data on backend:

public function store()
{
    $fields = collect(Input::get('reporting'));

    $fields->map(function($value, $key){

        return Reporting::create([

            'user_id'=>1,

            'reporting'=>$value,
        ]);

    });

   return redirect('/')->with('success', 'Action was successful');
}

This will produce the data in this format:

user_id || reporting
1           Salman
1           Ankur  

Note: Tested working correctly!

查看更多
在下西门庆
3楼-- · 2019-08-01 08:37

As $report is an array, current item of it can be received with [] notation:

$report = Input::get('reporting');

for($i=0; $i<=count($report);$i++)
{
    $news = new Reporting();
    $news->user_id = 1;
    $news->reporting = $report[$i];    // here add [$i]
    $news->save();
}
查看更多
登录 后发表回答