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.
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.
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?
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.
if(filter_var(Input::get('attending_lan'), FILTER_VALIDATE_BOOLEAN)){
The FILTER_VALIDATE_BOOLEAN filter validates value as a boolean option.
Possible return values:
source: http://www.w3schools.com/php/filter_validate_boolean.asp
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.