Search

Laravel 4: Working With Checkboxes and Input

April 1, 2014 —John Koster

Inside of a Blade view, a checkbox can be created using the Form class:

1{{ Form::checkbox('my_checkbox', '1') }}

In the above code sample, my_checkbox is the name of the input element and 1 is the value the checkbox was given. This would generate (with Laravel 4.1.*) the following HTML code:

1<input checked="checked" name="my_checkbox" type="checkbox" value="1">

#Checking if a Checkbox is Checked

Inside of a controller, there is a simple test that can be done to determine if a checkbox was indeed checked. This is by using a simple if statement:

1<?php
2 
3// ...
4 
5if (Input::get('my_checkbox') === '1')
6{
7 // Checkbox is checked
8}
9else
10{
11 // Checkbox is not checked
12}

In the above code sample, my_checkbox is the name of the input element and 1 is the value given to the checkbox input.

Setting the Checked State

After a user has submitted some data, it is important to restore the checked state of the input element. This way, if they checked a box, and come back to the page later (let's say that they checked a box saying a supplier or vendor was active) they would want to see that the checkbox was still checked.

A third argument can be passed to the checkbox function. This third argument should evaluated to a boolean value (true or false). This will cause the HTML to output the necessary HTML to make the checkbox checked on the screen:

1{{ Form::checkbox('my_checkbox', '1', $supplier->active) }}

In the above code sample, $supplier is just an example class that has an active property. This active property evaluates to a true or false value.

But what about old input? The Input::old() function can be used in conjunction with the checkbox function to create something like this:

1{{ Form::checkbox('my_checkbox', '1', Input::old('my_checkbox', $supplier->active)) }}

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.