Skip to content
Advertisement

How to validate at least one checkbox is checked in a loop in Laravel?

I’m trying to validate my checkbox from a loop, where at least one is checked and displays an error/alert or disable the submit button instead if there is no checkbox checked. I tried putting a required method inside my checkbox, but the checkbox is in a loop that’s why it requires all to be checked. That’s why I tried the script code below which I found on the internet but that doesn’t seem to work for me.

Below is my code in blade form

JavaScript

This is also the code in my controller, other data such as names are also part of the form but I cut it out by focusing on the checkbox

JavaScript

Advertisement

Answer

There are a many ways to achieve your desired result, how I would approach it is as follows (note this is not exhaustive, it’s a functional example).

On the client, use JavaScript to select all your product checkboxes, iterate over any found and attach event handlers to each of them which listen for the changed event (i.e. checked and unchecked). When the state of a checkbox is checked, add it to a Set so that we can track how many are selected. Based on the number of checked checkboxes, enable/disable form submission.

That theory out of the way, some code:

HTML:

JavaScript

JavaScript:

JavaScript

Example CodePen

Now lets apply the above to a Laravel example using @foreach and Eloquent models. I am going to assume you already have a Product model, migration and some data seeded.

Form HTML:

JavaScript

As we all know you shouldn’t rely soley upon client side validation, so you’ll want to do some server side validation too. Once you’ve validated your request data, you can do whatever you want with it (I just get the products from the database in this example). I have put the code directly in a Route within web.php as I am lazy, you’d obviously use it in your ProductController function.

routes/web.php:

JavaScript

Example PHP Sandbox

Quite a lot to taken in but hopefully that makes sense.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement