Laravel how to test if a checkbox is checked in a controller

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') ){
        //...
    }
}

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


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

Tags:

Php

Laravel