Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle unchecked checkboxes in Laravel?

I have an edit form with several checkboxes in Laravel. When I check the boxes and update the record, it works correctly, but if I uncheck the box it doesn't return any value so the record doesn't update and the value remains true in the database.

How can I handle unchecked checkboxes in Laravel?

like image 803
Allfarid Morales García Avatar asked Feb 15 '18 05:02

Allfarid Morales García


People also ask

What is the value of checkbox when unchecked?

Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked ); the value is not submitted to the server at all.


1 Answers

The best way I can think of is using ternary and null coalesce PHP operators:

$request->checkbox ? 1 : 0 ?? 0;

This will return 1 if checked, 0 if not checked or not available.

like image 188
Mr.Web Avatar answered Sep 19 '22 08:09

Mr.Web