Why is there an error when updating or editing data in Laravel using a data array, like this error.
foreach() argument must be of type array|object, string given
Database in MySQL:
Screenshot my Database in MySQL
Code:
Controller:
public function UpdateGradeStudent(Request $request){
$data = GradeDetail::find($request->id_grade_detail);
foreach($request->get('id_grade') as $index => $value) {
GradeDetail::updated([
$data->quiz =>$request->quiz[$index],
$data->assignment => $request->assignment[$index],
$data->d_t => $request->d_t[$index],
$data->min_text => $request->min_text[$index],
$data->final_text => $request->final_text[$index],
$data->total => $request->final_text[$index],
]);
}
return redirect('teacher/data-grade');
}
Blade:
form method="POST" action="{{route('edit.teacher.grade')}}" enctype="multipart/form-data">
@csrf
<input type="hidden" name="id_grade" value="{{ $userGrades->id_grade }}">
<div >
<input type="submit" type="button" value="Save">
<a href="{{url('teacher/data-grade')}}" type="button" >Cancel</a>
</div>
<table >
<tbody>
@forelse($subject as $data)
<tr >
<th scope="row" >
<input
type="number"
min="0"
max="100"
name="quiz[]"
id="quiz"
value="{{$data->quiz}}"
autocomplete="quiz"
required
>
</th>
<th scope="row" >
<input
type="number"
min="0"
max="100"
name="assignment[]"
id="assignment"
value="{{$data->assignment}}"
autocomplete="min_score"
required
>
</th>
And how or which part of the error to be able to update data using an array?
CodePudding user response:
You have to change id_grade hidden input like this
<input type="hidden" name="id_grade[]" value="{{ $userGrades->id_grade }}">
CodePudding user response:
$request->get('id_grade')
will return the value of id_grade
which will be a string as mentioned by @zohrehda. Please update your foreach loop to be
foreach($request->all() as $index => $value) {
$request->all()
returns an array of all your inputs which can be iterated upon.
Additionally, your update
method has a typo. It should be GradeDetail::update
and not GradeDetail::updated
.