简体   繁体   中英

PHP / Laravel 4 echo checkbox value from database stored as boolean

I have a few checkboxes that are stored as 0 for unchecked or 1 for checked as booleans.

I am now trying to echo back the values using laravel such as

echo $request->facebook

Which returns 1 or 0. It does not return the value of "facebook".

In my view I have:

<input type="checkbox" value="facebook" name="facebook" class="css-checkbox" />

In my model I have this:

$request->facebook = Input::has('facebook');
$request->save();

The model will check the form for the checkbox facebook and saves the boolean value in the database.

What is the best way to echo "facebook" if the checkbox was checked or echo out nothing, if the checkbox was unchecked?

This is what I do for checkboxes in my controllers:

$object = new MyObject;

$object->facebook = Input::has('facebook') ? 1 : 0;
$object->twitter = Input::has('twitter') ? 1 : 0;
$object->somethingElse = Input::has('someCheckbox') ? 1 : 0;

$object->save();

There may be better ways to do it but this is what I typically do. It's easy to read and understand and keeps your code organized.

I've experimented with moving things like this into the model using mutators, but I was kind of unsure about using the Input class on the model. In your controller POST method, the Input class is always going to be there. There is always going to be Input to check and use. But on some random model method, it's possible that you may access that method someday outside of a POST request and then there is no post input, so things like Input::has() will return false and set those values to zero.

There may be a more elegant way to do it. I'm not sure what though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM