0

控制器

 public function getScore(Request $request, $id)
{
   // $scores = Criteria::find($id);
    $contestants = Contestant::find($id);
    foreach ($request->criteria as $id => $criteria){
        $criteriaModel = Score::find($id);

        $scores = new Score();
        $scores->judge_name = $request->input('judge_name');
        $scores->contestant =  $contestants->name;
        $scores->criteria = $criteriaModel->criteria;
        $scores->score = $scores->score;
        $scores->save();
    }
    return redirect('/tabulation')->with('status', 'Score saved!');
}

      @foreach ($criterias as $criteria)
                                       <div class="form-group col-md-6">
                                           <label for="{{$criteria->name}}">{{$criteria->name}} </br> (0 - {{$criteria->points}})</label>
                                           <input type="text" name="criteria[{{$criteria->id}}][criteria]" value="{{$criteria->name}}" hidden>
                                           <input type="text" name="score[{{$criteria->id}}][score]" class="form-control" placeholder="Input score" required>
                                       </div>
                                   @endforeach
4

2 回答 2

0

表单字段名称可以包含括号以存储单个名称的多个属性:

@foreach ($criterias as $criteria)
    <div class="form-group col-md-6">
        <label for="{{$criteria->name}}">{{$criteria->name}} </br> (0 - {{$criteria->points}})</label>
        <input type="text" name="criterias[{{$criteria->id}}][name]" value="{{$criteria->name}}" hidden>
        <input type="text" name="criterias[{{$criteria->id}}][points]" class="form-control" placeholder="Input score" max="{{$criteria->points}}" name="score" required>
    </div>
@endforeach

上述形式将产生$request->criterias包含以下值的变量:

array:2 [▼
  1 => array:2 [▼
    "name" => "test"
    "points" => "dd"
  ]
  2 => array:2 [▼
    "name" => "tes22t"
    "points" => "sdsd"
  ]
]

该值可以在控制器中用于创建多个分数:

  foreach ($request->criterias as $id => $criteria){
            $criteriaModel = Criteria::find($id);

            $scores = new Score();
            $scores->judge_name = $request->input('judge_name');
            $scores->contestant =  $contestants->name;
            $scores->criteria = $criteriaModel->name;
            $scores->score = $criteria->points;
            $scores->save();
        }
于 2019-08-31T14:18:17.810 回答
0

首先,您必须将输入的名称更改为像这样的数组:

<input type="text" name="criteria[]" value="{{$criterias->name}}" hidden>

在您的控制器中,您必须循环输入:

foreach ($request->input('criteria') as $criteria){
    $scores = new Score();
    $scores->judge_name = $request->input('judge_name');
    $scores->contestant =  $contestants->name;
    $scores->criteria = $request->input('criteria');
    $scores->score = $request->input('score');
    $scores->save();
}
于 2019-08-31T14:20:06.437 回答