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