php 如何在laravel eloquent中保存布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41070382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:18:53  来源:igfitidea点击:

How to save boolean values in laravel eloquent

phplaravelcheckboxlaravel-5eloquent

提问by Alexander Solonik

I have made the following migration in Laravel:

我在 Laravel 中进行了以下迁移:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class QualityCheckTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('quality_check', function (Blueprint $table) {
            $table->increments('id');
            $table->boolean('favicon');
            $table->boolean('title');
            $table->boolean('image-optimization');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('quality_check');
    }
}

I have the following controller method that runs when the form in the frontEnd is submitted:

当提交前端中的表单时,我有以下控制器方法运行:

public function store(CreateArticleRequest $request) {
        // $input = Request::all();
        Article::create($request->all());
        return redirect('articles');
    }

My form looks like , so:

我的表格看起来像 ,所以:

{!! Form::open([ 'action' => 'QualityCheckController@validateSave' , 'class'=>'quality-check-form' , 'method' => 'POST' ]) !!}

        <div class="input-wrpr">
            {!! Form::label('favicon', 'Favicon') !!}
            {!! Form::checkbox('favicon', 'value' ); !!}
        </div>

        <div class="input-wrpr">
            {!! Form::label('title', 'Page Title') !!}
            {!! Form::checkbox('title', 'value'); !!}
        </div>

        <div class="input-wrpr">
            {!! Form::label('image-optimization', 'Image Optimization') !!}
            {!! Form::checkbox('image-optimization', 'value'); !!}
        </div>

        {!!  Form::submit('Click Me!') !!}

    {!! Form::close() !!}

So when the method runs the values of the checkboxes are saved to the database.

因此,当该方法运行时,复选框的值将保存到数据库中。

As of now , all entries are showing as 0, Like so:

截至目前,所有条目都显示为0,如下所示:

enter image description here

在此处输入图片说明

Now how to make it such that when the checkbox is checked , 1is saved and when the checkbox is left unchecked the value in is left at 0??

现在如何做到这样,当复选框被选中时,1被保存,当复选框未被选中时,值保留在0??

采纳答案by Jonathon

When a checkbox is ticked, it's value is present in the posted data. When it is unticked, it's value is not present. This means when you do $request->all()it will contain only the checkboxes that were ticked. So in your case, if you leave all 3 checkboxes unticked, your $request->all()could yield an empty array (Assuming that no other fields are posted).

当一个复选框被勾选时,它的值出现在发布的数据中。当它没有被勾选时,它的价值不存在。这意味着当你这样做时,$request->all()它只会包含被勾选的复选框。因此,在您的情况下,如果您未选中所有 3 个复选框,则$request->all()可能会产生一个空数组(假设未发布其他字段)。

When you run Article::create($request->all());with no checkboxes ticked you would be essentially passing it an empty set of data, which means that your database is going to be populated with the default values for the fields that you didn't provide.

当您在Article::create($request->all());没有勾选复选框的情况下运行时,您实际上将向它传递一组空数据,这意味着您的数据库将使用您未提供的字段的默认值填充。

Since you didn't provide a default in your migration, MySQL is going to guess what the default should be based on the field type, which in the case of a boolean will be 0. You may see some warnings/errors though.

由于您没有在迁移中提供默认值,MySQL 将根据字段类型猜测默认值应该是什么,在布尔值的情况下为0. 不过,您可能会看到一些警告/错误。

There are loads of ways you can get this to work so that a 1is saved when a checkbox is ticked or 0when it is not ticked. The easiest way in your scenario would be to set the value of each checkbox to be 1and explicitly set up default values in your migration i.e.

有很多方法可以让它工作,以便1在勾选或未勾选复选框时保存 a 0。在您的场景中,最简单的方法是将每个复选框的值设置为1并在迁移中明确设置默认值,即

Migration:

移民:

$table->boolean('favicon')->default(0);

Form:

形式:

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

This way, when the title checkbox is ticked, your $request->all()returns an array containing an item 'title' => '1'and this is saved in your database. All of the unticked boxes are defaulted to 0 as per your migration.

这样,当标题复选框被勾选时,您$request->all()将返回一个包含项目的数组,并将其'title' => '1'保存在您的数据库中。根据您的迁移,所有未勾选的框默认为 0。

I prefer however to be more explicit when I write my method for handling the store.

然而,当我编写处理 store 的方法时,我更喜欢更明确。

$article = new Article();
$article->title = $request->has('title'); // Will set $article->title to true/false based on whether title exists in your input
// ...
$article->save();

回答by René Juul Askj?r

Have you remembered to pass them in the $fillablearray in the Article Model?

你记得$fillable在文章模型的数组中传递它们吗?

protected $fillable = [
    'favicon',
    'title',
    'image-optimization'
];

and as a sidenote to the checkboxes thing. You can just make a hidden input with the same name, and make it false. That way, if the checkbox is unchecked, it will be false, but if it is checked, it will return true, as it is the last value:

并作为复选框的旁注。您可以使用相同的名称创建一个隐藏的输入,并将其设为 false。这样,如果复选框未选中,它将为 false,但如果选中,它将返回 true,因为它是最后一个值:

    <div class="input-wrpr">
        {!! Form::label('title', 'Page Title') !!}
        {!! Form::hidden('title', false); !!}
        {!! Form::checkbox('title', 'value'); !!}
    </div>

回答by Alexey Mezenin

You can check if checkbox is set with isset($request->favicon)or empty($request->favicon)or ->has('favicon'):

您可以检查是否复选框被设定isset($request->favicon)empty($request->favicon)->has('favicon')

public function store(CreateArticleRequest $request) {
    foreach (['favicon', 'title', 'image-optimization'] as $box) {
        $request($box) = $request->has($box);
    }
    Article::create($request->all());
    return redirect('articles');
}