Kimson Dooland
Kimson Dooland

Reputation: 55

How to pass a boolean value in Laravel from a form to the Database?

I tried checkbox it passes on when the checkbox is clicked. Is there no way to pass a boolean value in laravel from a form in laravel ?..

Upvotes: 3

Views: 8701

Answers (6)

jumps4fun
jumps4fun

Reputation: 4132

I needed an actual true or false to be sent, because a validation method wouldn't accept true or nothing. Here is what I did.

<input type="hidden" name="myBoolean" value="0">
<input type="checkbox" name="myBoolean" value="1">

this above returns 0

if you check the checkbox, and the DOM looks like this

<input type="hidden" name="myBoolean" value="0">
<input type="checkbox" name="myBoolean" value="1" checked>

Now the second named element with the same name overwrites the first, and it returns 1.

litteral true/false would work as well

I''l be honest. I don't think this is a best practice approach. It is a quite clean easy to read, simple workaround though.

Upvotes: 0

Kimson Dooland
Kimson Dooland

Reputation: 55

I used eloquent mutators in laravel to solve this...

 public function setOpenTodayAttribute($value)
    {
            $this->attributes['open_today'] = ($value=='on')?($value=1):
            ($value=0);
    }

if the value is on i,e checked $value=='on' it will be set to1which is *boolean* else it will be set to 0 which is false

Upvotes: 2

Amarnasan
Amarnasan

Reputation: 15529

Define an eloquent mutator like this in your model (\App\MyModelName.php):

public function setXXXAttribute($value)
{
        $this->attributes['xxx'] = ($value=='on');
}

where "XXX" is the tame of the database column.

The attribute xxx will be set to true in case the value of the checkbox is 'on'

Upvotes: 3

Hia Yongkuy
Hia Yongkuy

Reputation: 79

Do you mean Model's Attribute Casting? https://laravel.com/docs/5.5/eloquent-mutators

Upvotes: 0

Vahe Shak
Vahe Shak

Reputation: 1077

Add in your form

{!! Form::checkbox('checkbox_name', '1'); !!}

When the checkbox_name is clicked, you can get value from $request->all() array by 'checkbox_name'. Or

$checked = $request->has('checkbox_name')

Upvotes: 1

Galironfydar
Galironfydar

Reputation: 171

When submitting the Form give the checkbox a value of true. This will then be passed through the form data.

<input type="checkbox" name="checkbox_name" id="checkbox" value="true"/>

Upvotes: 2

Related Questions