4

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213

2 Answers2

4

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

Try this in your controller:

$page = Page::where('user_id', 1);
if( $request->has('show_header') && $request->show_header == 1 ){
    $page->update(array_add($request->all(), 'show_footer', 0));
}else{
    $page->update(array_add($request->all(), 'show_header', 0));
}
Kabelo2ka
  • 419
  • 4
  • 14