How To Show Checkbox Value Checked

In this post, we will work on checkbox status while updating the post. This example is very similar to other if-else statements.

Your table column will be false by default. It will store 0 in the database if not checked.

$table->boolean('visible')->default(false);

For the entry form it will be something like this:

<input type="checkbox" name="visible" value="1">

Show checkbox checked

Now the main part here is to show checked when updating if there is a true value store that is 1 and not to show checked if there is a false value that is 0.

Example 1

Simple Laravel checkbox selected with the ternary operator

<input type="checkbox" name="visible" value="1" {{ $page->visible ? 'checked' : '' }}>

Laravel checkbox selected with the ternary operator and compare boolean values.

<input type="checkbox" name="visible" value="1" {{ $page->visible==1 ? 'checked' : '' }}>

Another way to check the same thing is with the true or false values we have used above for boolean values.

<input type="checkbox" name="visible" value="1" {{ $page->visible==true ? 'checked' : '' }}>

Example 2

There are other ways to do the same. You can always use the if-else statement to show if something is true or false. If-else statement will be messy and why not use the better few lines to complete the long path?

We can use the same statement within the input tag. Select the checkbox with the @if blade directives.

<input type="checkbox" name="visible" value="1" @if ($page->visible) checked @endif>

The thing with a shorter version by @checked blade directives.

<input type="checkbox" name="visible" value="1" @checked ($page->visible)>

Related Posts