@inquisitvewaffle Well as mentioned when you brought this up on Discord a couple of hours ago, you do have a model: rating, and your assessment would have many of them. So loop over the checked ratings and create a rating for each.
Save Checkbox Array to Database in Laravel 8
Hey Folks,
I am looking for advice on how to store a checkbox array from a form into a database, but rather than using json_encode or implode which put it all into a single row, I want to have each array value appear in its own row , associated with the form submission (known as an assessment in this case).
For more context, the checkboxes (Ratings) are valued 1-10 and for each form submission a user can select multiple checkboxes. With this in mind, I am thinking this is a hasMany relationship between Assessment and Ratings but not sure how this works you don't have two existing tables as with a pivot table.
Additionally, the checkbox number values are fixed so they do not exist in a table.
Happy to share Models, Views, and Controllers but wanted to put this out generally to get advice.
@inquisitvewaffle I think you’re massively over-complicating the problem.
You have assessments. You want to store many ratings for a single assessment. That’s just a run-of-the-mill, has-many relation. So for each rating submitted, save a rating in the database for the associated assessment:
// $request->input('ratings') is an array of checked ratings, i.e.
// [1, 2, 5, 6]
foreach ($request->input('ratings') as $rating) {
// Given an Assessment model, save an associated rating per checked rating
$assessment->ratings()->create([
'rating' => $rating,
]);
}
Please or to participate in this conversation.