Reputation: 366
Here's the flow: I select up to 5 students in a listing and click the "Generate Training" button.
Then I record in the session an array of the selected students.
In the next screen I retrieve this array and render a list with a checkbox called "Attended" where you can select whether the student went to training or not. By clicking on the "Record Training" button I must update the students who attend the training. So far so good.
The problem is, I can't update the original array that contains all the students. For example, if 5 students were selected but only 3 attended the training, I should update the training of those students in the database and update the original array, keeping the data that was not changed along with the data that was changed.
The code below shows how I am trying to upgrade the main array (with all students selected). The code is commented, including the errors that appear:
// dd($ar_student); //ARRAY WITH STUDENTS WHO ENJOYED TRAINING
// dd($all_students);//ARRAY WITH ALL SELECTED STUDENTS (MAY BE FROM 1 TO 5)
foreach($all_students as $item1){//I GO ARRAY TO ALL STUDENTS
foreach($ar_student as $item2){//I GO TO ARRAY THE STUDENTS ATTENDING
// dd($item1->student_id);
if($item1->student_id == $item2->student_id){//IF IDS ARE EQUAL
// dd($item2);
$all_students->fase_id = $item2->fase_id;//UPDATE ARRAY WITH ALL STUDENTS (REALLY I NEED TO UPDATE STUDENT PHASE ONLY). ERROR AT THIS LINE: Attempt to assign property of non-object
}
}
}
$students = $all_students;
//dd($all_students);
Upvotes: 1
Views: 1331
Reputation: 86
Your error came from trying to set the "fase_id" property of the array ($all_students) instead of "item1".
//You should be setting
$item1->fase_id = ...
//instead of
$all_students->fase_id =
Also, if you create an associative array (the student id being the key) you could only use one loop. If your array $ar_student is [student_id => student] then :
foreach($all_students as $item1){
if( isset($ar_student[$item1->student_id]) ){
$item1->fase_id = $ar_student[$item1->student_id]->fase_id);
}
}
Upvotes: 1
Reputation: 1539
The reason of the error is $all_students->fase_id
because all_students
is collection, therefore you can do two things here to fix the error. if you really want to keep $all_student
update first foreach
and $all_students[$key]->fase_id
like below,
foreach($all_students as $key => $item1){
foreach($ar_student as $item2){
if($item1->student_id == $item2->student_id){
$all_students[$key]->fase_id = $item2->fase_id;
}
}
}
Otherwise use $item1->fase_id
like below,
$item1->fase_id = $item2->fase_id;
Upvotes: 1
Reputation: 382
Yor are probably getting errors on that line, because you are trying to set property on array
$all_students->fase_id = $item2->fase_id;
You should change it to
$item1->fase_id = $item2->fase_id;
Upvotes: 1