Save unchecked Checkbox I have a form which is just a series of checkboxes. This works fine.
I then want to edit the form but if I want to uncheck a box this does not get sent through the request, only checked boxes do. How can I store that?
@sarahs74 you can check if the request has value for the particular checkbox like this:
$request->has('checkbox_name')
this will return either true or false.
You can use ->has() to check if it is checked or not
$checkbox = $request->has('mycheckbox');
I tried that for the first checkbox and even when I untick it it still comes back as true.
Can you share how you are assigning to that property whenever you handle the form?
Could you share some code then? Using has is the normal method of doing this, so it should work
Make sure you don't have another input with the same name as the checkbox :)
OK so I removed all the other checkboxes to see if there was a conflict and the first checkbox came back as false, so I put everything back in to find the issue. I couldn't see any conflict so I ran it again and it still came back as false. Tried changing all of them a few times and outputting the result and everything is OK. No idea why.
So anyway, now I have 6 variables all coming back with either true or false which is great but how do I now update my database when the original code was just:
$enhanceddiligence->update($request->all());
@sarahs74 well, you can merge two arrays in the update, separating the checkboxes out so that it gets the correct value:
$enhanceddiligence->update(
$request->all()
+
[
'checkbox1' => $request->has('checkbox1'),
// ... the rest of the checkboxes here.
]
);
You need to handle them one at a time then :)
$checkboxes['mycheck1'] = $request->has('mycheck1');
$checkboxes['mycheck2'] = $request->has('mycheck2');
$checkboxes['mycheck3'] = $request->has('mycheck3');
$enhanceddiligence->update($checkboxes);
quick fix, try hidden input...
<input type="hidden" name="box1" value="0" />
<input type="checkbox" name="box1" value="1" />
Very elegant, it makes this input behave like the others
Please sign in or create an account to participate in this conversation.