Laravel添加动态输入字段

时间:2017-11-26 13:50:49

标签: php laravel bulkinsert laravel-eloquent

我想在DB中插入动态字段。我使用以下代码,但它没有按预期工作。

<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  

请你帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

void del()                  `
{
    char *str;
    FILE *fp;
    char ch[20],ch1[20];
    fp=fopen("database.txt","a");
    printf("enter roll to be deleted:");
    scanf("%s",&ch1);
    while(fscanf(fp,"%s",ch)!=EOF)
{
    if(strcmp(ch,ch1)==0)
    {
    str=&"%s";
    free(str);
    }
}

在后端捕获数据:

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

注意:测试工作正常!