16

I am trying to see if a checkbox is checked or not in my controller. I've read that this is the code to do it

if (Input::get('attending_lan', true))

But that returns true even if the checkbox is unchecked.

Brennan Hoeting
  • 1,213
  • 6
  • 18
  • 28

4 Answers4

27

Use Input::has('attending_lan')

Generally speaking, if the checkbox is checked, the request variable will exist. If that is not the case you have a problem somewhere else in the code.

Also relavant: Does <input type="checkbox" /> only post data if it's checked?

Community
  • 1
  • 1
cen
  • 2,873
  • 3
  • 31
  • 56
15

Assuming you have this form code in your view:

// view.blade.php
{{ Form::open() }}
    {{ Form::checkbox('attending_lan', 'yes') }}
    {{ Form::submit('Send') }}
{{ Form::close() }}

You can get the value of the checkbox like this:

if (Input::get('attending_lan') === 'yes') {
    // checked
} else {
    // unchecked
}

The key here is that you have to set a value when creating the checkbox in your view (in the example, value would be yes), and then check for that value in your controller.

Manuel Pedrera
  • 5,347
  • 2
  • 30
  • 47
  • 1
    It should also be noted that if attending_lan is unchecked, you will not get an error. This differs from standard PHP where if you query an unchecked attending_lan you get variable not found. – Relaxing In Cyprus Feb 03 '14 at 19:57
-1
if(filter_var(Input::get('attending_lan'), FILTER_VALIDATE_BOOLEAN)){

The FILTER_VALIDATE_BOOLEAN filter validates value as a boolean option.

Possible return values:

  • Returns TRUE for "1", "true", "on" and "yes", and uppercase versions.
  • Returns FALSE for "0", "false", "off" and "no", and uppercase versions.
  • Returns NULL otherwise.

source: http://www.w3schools.com/php/filter_validate_boolean.asp

malhal
  • 26,330
  • 7
  • 115
  • 133
-2

An alternative is to check the array key to see if it exists, given that when not checked an Input::get('key') might give you problems given its an undefined index in the Input array.

$input = Input::all();
if(array_key_exists($input('key',$input)){
// Checked
}else{
// Not Checked
}

Or .. something like that. I'm a bit sloppy but I hope it can help someone.

FerBorVa
  • 1
  • 6