I'll-Be-Back I'll-Be-Back - 12 days ago 9
PHP Question

Unchecked checkboxes value request?

I have

show_header
and
show_footer
fields in the database, the value can be 1 or 0.

<input type="checkbox" name="show_header" checked="checked" value="1">
<input type="checkbox" name="show_footer" checked="checked" value="1">


Assume
show_header
and
show_footer
is set to 1 in the database and you uncheck the both of them in the form, the request inputs will not contain
show_header
and
show_footer
fields because it is not selected.

So how can I get around this to update
show_header
and
show_footer
to 0 in the database?

Example :

$page = Page::where('user_id', 1);

$page->update($request->all());


If you do:

dd($request->all())


You will not find
show_header
and
show_footer
since checkboxes are not checked, so by doing
$page->update($request->all());
it can't set
show_header
and
show_header
to 0 in the database.

Answer

You could check before update and set the default value to 0 so if the attributes are not here just set them to 0:

$page = Page::where('user_id', 1);

$data = $request->all();
$data['show_header'] = $request->input('show_header',0);
$data['show_footer'] = $request->input('show_footer',0);

$page->update($data);  

Hope this helps.

Comments