Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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 my web.php:

Route::post('/admin/role/add', 'AdminController@createRole')

but doesn't work for some reason.

How i can do?

Thanks for reply.

EDIT 1 :

It was my form that was poorly build.

like image 841
loic.lopez Avatar asked Nov 03 '16 21:11

loic.lopez


People also ask

How to check if checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you pass checkbox value 0 if not checked and 1 if checked?

How do you pass checkbox value 0 if not checked and 1 if checked? Add a hidden input that has the same name as the checkbox with the value of 0 BEFORE the checkbox. If the checkbox is unchecked, the hidden field value will be used, if it is checked the checkbox value will be used.

How to check if checkbox is checked jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

What is check in PHP?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.


1 Answers

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

like image 57
Peon Avatar answered Sep 29 '22 15:09

Peon