当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Laravel 5, how to test if a Checkbox is checked in a controller

问题描述:

i tried to get if checkbox is checked with :

In my view :

 <form data-toggle="validator" data-disable="false" role="form" action="/admin/role/add" method="post">

<div class="checkbox checkbox-success">

<input name="test" id="test" type="checkbox" value="test">

<label for="test" style="padding-left: 15px!important;">test</label>

</div>

</form>

<form data-toggle="validator" data-disable="false" role="form" action="/admin/role/add" method="post">

{{ csrf_field() }}

<div class="form-group pull-right">

<button type="submit" class="btn btn-danger">Submit</button>

</div>

</form>

In my controller :

public function createRole(Request $request)

{

if( $request->has('test')) {

new \App\Debug\Firephp('test', ['test' => true]);

}

}

in web.php :

 Route::post('/admin/role/add', '[email protected]')

but doesn't work.

How i can do ?

Thanks for reply.

EDIT 1 :

It was my form that was poorly build

网友答案:

I believe your real problem is that you have two separate forms. Your checkbox is in one form, your submit button is in a second form. I believe they both need to be in the same form. Otherwise your checkbox state is never returned, regardless of it's state.

In your view, try replacing the form markup you provided with this:

<form data-toggle="validator" data-disable="false" role="form" action="/admin/role/add" method="post">
    <div class="checkbox checkbox-success">
        <input name="test" id="test" type="checkbox" value="test">
        <label for="test" style="padding-left: 15px!important;">test</label>
    </div>
    {{ csrf_field() }}
    <div class="form-group pull-right">
        <button type="submit" class="btn btn-danger">Submit</button>
    </div>
</form>
网友答案:

Checkbox sends info only when it's checked, so what you do is, you check, if the value is present. It's easier, if you use method with Request $request than using direct inputs:

if (isset($request->test)) {
    // checked
}

Laravel docs: https://laravel.com/docs/5.0/requests

网友答案:

You can test it with:

if( Input::get('test', false) {
    // there is something for 'test'
} else {
    // there was no 'test' or it was false
}

Or,

if( Request::input('test') ) { //...

Or,

public function store(Request $request)
{
    if( $request->has('test') ){
        //...
    }
}

Says, https://laravel.com/docs/5.0/requests

分享给朋友:
您可能感兴趣的文章:
随机阅读: