Checkboxes and the logic behind updating them

My task for the day was to build checkboxes of all the categories available for the posts. One post may have multiple categories. The first thing to do was to build a form where the multiple checkboxes are dynamically available and add them to the post-category relationship table (add only the id of both post and category). This was fairly easy as we just had to capture the value as an array of ids of all the categories that are ticked and store them on the database.

Then the next step was the editing part. The part where we show all the values of the post. This is also an easy part as we just have to show the values that are already stored on the database. To clarify I would like to also include that the post category relationship has three tables one with post category relationship id, another with post category id and post id.

Now comes the tricky part. I first tried to update the values in the checkboxes by updating only those with the same post id but that changed all the values to the same value, so it didn’t work. For example, if there were three categories in the same post, all those categories would be updated to the same category.

Then, I first compared the edited values with the values that are already in the database and updated them by comparing both values. Here, I compared both the edited with the values that are post category id value and post id value. This somewhat worked but another problem arose. If an already checked box of a category was unchecked that wouldn’t update.

To overcome this problem, I tried to update the values as per post id but it was the first problem all over again. I needed some way to remove the value that is unchecked so that the unchecked category value wouldn’t be retrieved.

After lots of brainstorming and doing lots of things I couldn’t update checkboxes.

So I asked my colleague and we came up with a solution.

The simple solution was to delete all the values associated with the post id and retrieve the values of the edited values and store them.

This was the simplest solution I could think of. Hope this helps.

Here is the link to some mistakes that you can make while uploading images in Laravel

If you want to know how to check if the checkbox is checked or not then please go through this article.

869 thoughts on “Checkboxes and the logic behind updating them”