Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4, how to test if a Checkbox is checked?

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.

like image 859
Brennan Hoeting Avatar asked Nov 23 '13 22:11

Brennan Hoeting


People also ask

How do you check if a checkbox is checked or not?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.

How can test if check box is set in PHP?

We can use the isset() function to check whether the checkbox is checked in PHP. The isset() function takes the $_POST array as argument. The $_POST array contains the specific value of the name attribute present in HTML form. For example, create a form in HTML with POST method and specify the action to index.

How do you pass checkbox value 0 if not checked and 1 if checked?

How do you pass checkbox value 0 if not checked and 1 if checked? Add a hidden input that has the same name as the checkbox with the value of 0 BEFORE the checkbox. If the checkbox is unchecked, the hidden field value will be used, if it is checked the checkbox value will be used.


2 Answers

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?

like image 132
cen Avatar answered Oct 19 '22 14:10

cen


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.

like image 22
Manuel Pedrera Avatar answered Oct 19 '22 16:10

Manuel Pedrera