Laravel checkbox is not submitted to controller

2019-07-16 12:00发布

问题:

I have a simple form in a view like this:

<form action="{{ URL::route('admin.x') }}" method="POST">
    <input type="text" value="b" name="title" />
    <input type="text" value="c" name="type" />
    <input type="text" value="d" name="postfix" />
    <input type="checkbox" name="check" value="ss" />
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

I used

dd(Input::all());

for checking all of values posted to controller from view. the result is like below and I want to know how to post checkbox value with form.

array:4 [▼

"title" => ""

"type" => ""

"postfix" => ""

"_token" => "kSM3pO11KOOWQcCx4PeWcbi4r4AsFx0rSGQoVFtG"

]

回答1:

A checkbox input is not submitted to the server side script if not checked by the user or by a client side script. So, in these cases, the input isn't sent to your controller

In laravel, if you want to 'normalize' somehow the situation when the input isn't sent, you can create a field by yourself:

$data = Input::all();

if ( ! isset($data['check'])
    $data['check'] = false; 


回答2:

You can ensure that your server side receives a value for the checkbox, regardless of whether it was checked, by creating a hidden input field with the same name above the checkbox field.

This way, if the form is submitted without the checkbox being checked, the server side will receive the value from the hidden input field whereas if the checkbox is checked the server will receive the checked value due to the field being lower in the form.

<input type="hidden" name="checkbox" value="0"/> <input type="checkbox" name="checkbox" value="ss"/>



回答3:

This returns true if the checkbox is checked, false if not.

Input:has('check')