Laravel 添加动态输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47496851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:00:54  来源:igfitidea点击:

Laravel add dynamic input fields

phplaravelbulkinsertlaravel-eloquent

提问by Muhammad Kazim

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.

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

采纳答案by u_mulder

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

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

回答by Leo

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!

注意:经测试工作正常!