Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

How to get checkbox value in a Laravel controller?

I have a checkbox in my form and I want to save its value into the database. When I check it, its value will be 1 and when I uncheck it then it's value will be 0. However, in the controller, I am getting NULL all the time. But why? Is it possible to solve without jQuery?

Blade/View

<form action="{{ route('admin.categories.store') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group>
       <label>
          <input type="checkbox" name="category_is_menu"
                 value="{{ old('category_is_menu', isset($category) ? 'checked' : '') }}"/>
       </label>
    </div>
    <input class="btn btn-success" type="submit" value="Submit">
</form>

Controller

public function store(Request $request)
{
    $category = new Category();
    $category->category_is_menu = $request->category_is_menu;

    return $category;
}

Unfortunately, it's giving me NULL for category_is_menu.

Upvotes: 2

Views: 13134

Answers (2)

N69S
N69S

Reputation: 17206

Add a hidden input with the negative value just before the checkbox input (with the same value in the name attribute)

<div class="form-group">
    <input type="hidden" name="category_is_menu" value="0"/>
    <input type="checkbox" name="category_is_menu" value="1" {{ old('category_is_menu', isset($category) ? 'checked' : '') }}/>
</div>

The value in the checkbox input needs to be always 1.

A checkbox input in not sent in the request when it's unchecked, in that case the hidden input will be sent with the value 0. When the Checkox is checked, it will overwrite the value to 1.

Upvotes: 7

lagbox
lagbox

Reputation: 50491

Either use the hidden input trick as mentioned in the other answers or just check if the input was passed at all. If it was passed at all it was checked, if its not there it was not checked:

$category->category_is_menu = $request->has('category_is_menu');

If it was checked you get true, 1, if it wasn't checked you get false, 0.

Upvotes: 6

Related Questions