How to store multiple values of checkboxes in database
I'm trying to store attendance of college students on single submit button, a teacher would mark 'present' or 'absent' checkbox, once all checkboxes are selected I want to store the values of these checkboxes as well as the id's of the student in the database. List of students is coming from the database using foreach() function.
If you want to use checkbox then create only one checkbox for present corresponding to each student, if checkbox is checked then student is present and by default it would be absent.
And you can use name for the checkbox like 'student1', 'student2' and so on for the student having Id 1, 2 and so on.
But if you want use present and absent then create radio button instead of checkbox, because same student can not be marked as present and absent (which is possible in case of checkbox) .
Only the checked boxes will have their value included within the form submission. It should come in as an array so you could do whatever processing you want with that.
//PSEUDO CODE
$students_present = $request->input('students_present');
foreach($students_present as $sp){
Student::is_present_today($sp)
}
@somnathsah, @YewNork Thank you so much for your answers. I'm still confused, as you suggested that I need to put student id# in the value attribute of checkbox Or radio button, then how could I get the status of absent and present because checkbox or radio button will send the student's id#, not absent or present status.
Sorry I didn't understand what you are trying to say about the logic problem?
Please please can you show the short code example which in your mind is a good to be done. I need this to be done very worried about it.
this will send all the present students to controller , no absents would be sent.
after you submit(or you can do ajax as you like). and the default value in your database of present is set to be False.
in controller, first always do validation. then
$ids = $request->present;
foreach ($ids as $id) {
$student = Student::findOrfail($id); // assume you use this model
$student->present = true;
$student->save;
}
maybe there is easier way , but this is i can figure now.
Thank you so much, lets say there are 10 student's, in which 8 student's are present. How can I store the other 2 absent students in Attendance table, because in attendance table there are no other records, there we are going to store all students attendance that whether they are absent or present? The above solution will add only those students who are present.