Laravel add dynamic input fields

。_饼干妹妹 提交于 2019-12-11 07:23:40

问题


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.


回答1:


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



回答2:


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!



来源:https://stackoverflow.com/questions/47496851/laravel-add-dynamic-input-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!