Laravel checkbox is not submitted to controller

2019-07-16 11:44发布

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"

]

3条回答
手持菜刀,她持情操
2楼-- · 2019-07-16 12:05

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楼-- · 2019-07-16 12:07

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

Input:has('check')
查看更多
聊天终结者
4楼-- · 2019-07-16 12:10

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; 
查看更多
登录 后发表回答