如何在laravel中雄辩地保存布尔值 [英] How to save boolean values in laravel eloquent

查看:80
本文介绍了如何在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');
    }
}

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

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

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

{!! 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() !!}

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

到目前为止,所有条目都显示为0,就像这样:

现在如何使它成为选中复选框时保存1,而取消选中复选框则将其中的值保留在0 ??

解决方案

选中复选框后,其值将显示在发布的数据中.取消选中时,它的值不存在.这意味着当您执行$request->all()时,它将仅包含已选中的复选框.因此,在您的情况下,如果未选中所有3个复选框,则$request->all()可能会产生一个空数组(假设未发布其他字段).

如果运行Article::create($request->all());时未选中任何复选框,则实际上将为它传递一组空数据,这意味着数据库将使用未提供的字段的默认值填充. /p>

由于没有在迁移中提供默认值,因此MySQL将根据字段类型猜测默认值,如果是布尔值,则默认为0.不过,您可能会看到一些警告/错误.

有很多方法可以使它起作用,以便在选中复选框时保存1,而在未选中复选框时保存0.在这种情况下,最简单的方法是将每个复选框的值设置为1,并在迁移过程中显式设置默认值,即

迁移:

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

表格:

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

此方式,当标题复选框被打勾,您的返回包含的项目的阵列和该被保存在数据库中.根据您的迁移情况,所有未勾选的框都默认为0.

但是,当我编写用于处理商店的方法时,我希望更明确一些.

$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();

I have made the following migration in 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:

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

解决方案

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).

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.

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.

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

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.

I prefer however to be more explicit when I write my method for handling the 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();

这篇关于如何在laravel中雄辩地保存布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆