Laravel 添加动态输入字段

Laravel add dynamic input fields

我想将动态字段插入到数据库中。我正在使用以下代码,但它没有像我预期的那样工作。

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

预期结果:

user_id || reporting
1           Salman
1           Ankur  

你们能帮我解决这个问题吗?

因为$report是一个数组,它的当前项可以用[]表示法接收:

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

您可以映射集合并创建新报告,同时按照您希望的方式存储报告值:

<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>

在后端捕获数据:

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');
}

这将生成以下格式的数据:

user_id || reporting
1           Salman
1           Ankur  

注意:经测试工作正常!