I wanna input checkbox with value 0 and 1, if i checked value 1, and if not checked value 0.
my code in View
@foreach($criteria as $data)
<table>
<tr>
<td class="col-4">
<input type="hidden" name="criteria_id[]" value="{{ $data->id }}">
{ $data->criteria_name}} :
</td><br>
<td class="col-2">
<input type="hidden" class="form-control" name="score[]" value="0">
<input type="checkbox" class="form-control" name="score[]" value="1">
</td>
</tr>
</table>
@endforeach
My code in Controller
for ($i=0; $i < count($request->criteria_id) ; $i ) {
$score_detail[] = [
//$detail_score = new DetailScoreModel(),
'score_id' => $getscoreid->id,
'criteria_id' => $request->criteria_id[$i],
'score' => $request->score[$i],
'description' => $request->description[$i]
];
}
and why the results in the database don't match ?
the correct result should be 1,1,0,1,1,0,1,1,1,1 but the stored data is 0,1,0,1,0,1,0,1,0,1
CodePudding user response:
You need to set the criteria_id as key for score. And remove hidden input for score.
Your view,
@foreach($criteria as $data)
<table>
<tr>
<td class="col-4">
<input type="hidden" name="criteria_id[]" value="{{ $data->id }}">
{ $data->criteria_name}} :
</td><br>
<td class="col-2">
<input type="checkbox" class="form-control" name="score[{{ $data->id }}]" value="1">
</td>
</tr>
</table>
@endforeach
Your controller, now check the score exist based on the criteria_id as bellow.
$criteria_ids = $request->criteria_id;
foreach ($criteria_ids as $i => $criteria_id) {
$score_detail[] = [
'score_id' => $getscoreid->id,
'criteria_id' => $criteria_id,
'score' => isset($request->score[$criteria_id]) ? 1 : 0,
'description' => $request->description[$i]
];
}