Multiple Divs based on selected number (LARAVEL)

问题: I have a problem with my code. According to another post: (Creating Multiple Divs Based on Number Chosen in Drop Down Menu ) I have taken some ideas for my code but I have...

问题:

I have a problem with my code. According to another post: (Creating Multiple Divs Based on Number Chosen in Drop Down Menu ) I have taken some ideas for my code but I have an issue. I want to insert into my datbase all the inputs from the created divs, but it records only the last div's inputs. This is my controller setup:

$generals= new Instance;

$generalsnames=implode("",$_POST['generalname']);

$generalstime=implode("",$_POST['generaltime']);

$generals->Name= $generalsnames;

$generals->Time= $generaltime;

$generals->save();

Can you help me? Thank you in advice


回答1:

as @rkg mentioned you need [] in your blade, then on your controller this will be your code.

$input = $request->all();
for($i=0; $i<count($input['generalname']); $i++)
{
    $generals= new Instance;
    $generals->Name= $input['generalname'][$i];
    $generals->Time= $input['generaltime'][$i];
    $generals->save();
}

回答2:

In your HTML(blade) code, add "[]" on your field names. So your field names should be as follows:

<input type="text" name="generalname[]">
<input type="text" name="generaltime[]">

instead of

<input type="text" name="generalname">
<input type="text" name="generaltime">

because only the last value of appended divs with such names will be included in your POST request to your route if you haven't specified an array for the names of your fields.

Then in your controller:

public function store(Request $request)
{
   $input = $request->all();
   //you might want to combine your arrays for easier saving
   $general_time = array_combine($input['generalname'], $input['generaltime']);

   //then you will use foreach statement to save all of your data
   foreach($general_time as $general => $time)
   {
      $generals = new Instance;
      $generals->Name = $general;
      $generals->Time = $time
      $generals->save();
   }
}

回答3:

I got it working.

I mixed the solutions by @Jovs and @rkg. After a few tweeks and restarting the server I got it working. Steps Followed:

  • Added [] into the name tags, in the blade.php
  • In the controller I put the code of @Jovs (in the for statement you missed a " ' ")
$input = $request->all();
for($i=0; $i<count($input['generalname']); $i++){
   $generals= new Instance;
   $generals->Name= $input['generalname'][$i];
   $generals->Time= $input['generaltime'][$i];
   $generals->save();
}

I got the "Array into string conversion" issue. I really didn't touched anything. I've just restarted the server, but later I got it working.

  • 发表于 2019-07-05 13:09
  • 阅读 ( 162 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除