laravelfor-looptextfieldstoring-information

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'score' cannot be null


Controller

 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!');
}

Blade

      @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

Solution

  • Form field names can contain brackets to store multiple properties for a single name:

    @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
    

    The above form would result the $request->criterias variable containing the following value:

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

    This value can be used in the controller for creating multiple scores:

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