1

What is the best practice for saving and updating a checkbox in Laravel?

I have set the boolean data type and a default values is 0 in migration file and if i try to save the checkbox i get this error:

Incorrect integer value: 'on' for column

and what about the update method also...

this is my checkbox in view file:

{!! Form::checkbox('clothing_supplied', null, isset($event) ? $event->clothing_supplied : 0, ['id' => 'check', 'class' => 'form-control' ]) !!}

and this is how i update

$event->update($request->all());
lewis4u
  • 14,256
  • 18
  • 107
  • 148

2 Answers2

2

This should do the trick:

$event->clothing_supplied = ($request->get('clothing_supplied') === 'on');

This should be added to your controller action or wherever you're updating your model.

This happens because the actual value submitted by the form is the string on instead of a boolean value.

Alternatively:

$all = $request->all();
$all['clothing_supplied'] = ($request->get('clothing_supplied') === 'on');
$event->update($all);
siannone
  • 6,617
  • 15
  • 59
  • 89
1

Try this

$request->replace(array('clothing_supplied' => (bool)$request->input('clothing_supplied')));

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

Only edit a single field based on a certain value

(bool)($request->input('clothing_supplied') == 'on') ? $event->update(['clothing_supplied' => 1]) : $event->update(['clothing_supplied' => 0]);

shoieb0101
  • 1,524
  • 10
  • 15
  • can i update only one field instead of $request->all()...for example $event->update(only clothing_supplied); – lewis4u Nov 27 '16 at 21:36
  • yeah, try using `$event->update(['clothing_supplied'=>$request->input('clothing_supplied')])` – shoieb0101 Nov 27 '16 at 21:38
  • well then this would be the best solution `$event->update(['clothing_supplied' => 1]);` – lewis4u Nov 27 '16 at 21:39
  • here you are setting the value to `1`. aren't you going to set the value from the form input? – shoieb0101 Nov 27 '16 at 21:40
  • i would do something like this: `$request->has('clothing_supplied') ? $event->update(['clothing_supplied' => 1]) : $event->update(['clothing_supplied' => 0]);` wouldn't that be good? – lewis4u Nov 27 '16 at 21:43
  • `$request->has` will return `true` even if the value is set to `0`. It checks if a given parameter is present or not – shoieb0101 Nov 27 '16 at 21:46
  • try `(bool)($request->input('clothing_supplied') == 'on') ? $event->update(['clothing_supplied' => 1]) : $event->update(['clothing_supplied' => 0]);` – shoieb0101 Nov 27 '16 at 21:48
  • thanks....i accepted siannones answer because he helped me in chat little more... – lewis4u Nov 27 '16 at 21:50
  • that's ok. happens a lot of time I guess! – shoieb0101 Nov 27 '16 at 21:54