欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

How to save boolean values in laravel eloquent migration 有大用

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:

enter image description here

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 ??






4 Answers 正确答案

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

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

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:

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

You can check if checkbox is set with isset($request->favicon) or empty($request->favicon) or ->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');
}

You can use mutators in the Laravel. Use this link and you'll get the idea :-

https://laravel.com/docs/5.3/eloquent-mutators

来自  https://stackoverflow.com/questions/41070382/how-to-save-boolean-values-in-laravel-eloquent





如何拯救laravel雄辩的布尔值

我作出了以下的Laravel移民:

<?PHP使用照亮数据库模式\ \ \的蓝图使用照亮\ \ \迁移数据库迁移qualitychecktable延伸迁移{/ ***运行迁移。* @返回void * /公共功能向上的(){图式::创造“quality_check”功能蓝图为表{为表-&#62;增量“身份证”);为表-&#62;布尔“图标”);为表-&#62;布尔“标题”);为表-&#62;布尔图像优化);});}/ ***逆向迁移。* @返回void * /公共功能向下(){图式::“quality_check”);}}

我有以下的控制方法,运行时在前台提交表单:

公共功能商店createarticlerequest要求美元{// $input = Request::all();文章::创造要求美元-&#62;全部());退货重定向&#39;文章&#39;);}

我的表像,所以:

{!!形式::开放([“行动”=>这是qualitycheckcontroller @ validatesave“类”=>质量检查表“方法”=>“后”])!!}<DIV=“输入wrpr”&#62;{!!形式::标签“图标”“图标”!!}{!!形式::复选框“图标”“价值”);!!}</DIV&#62;<DIV=“输入wrpr”&#62;{!!形式::标签“标题”页面标题!!}{!!形式::复选框“标题”“价值”);!!}</DIV&#62;<DIV=“输入wrpr”&#62;{!!形式::标签图像优化图像优化!!}{!!形式::复选框图像优化“价值”);!!}</DIV&#62;{!!形式::提交“我!”!!}{!!形式::关闭()!!}

所以当方法运行复选框的值保存到数据库。

截至目前,所有参赛作品展示,像这样:

enter image description here

现在怎么做,当该复选框被选中,保存时,复选框是听之任之的价值留在??


4个答案 正确答案


当一个复选框,它的价值是在发布数据。当它unticked,它的价值是不存在的。这意味着当你在request→(美元)它将只包含复选框被勾选。所以在你的情况下,如果你把所有的3个复选框unticked,你在request→(美元)可能会产生一个空数组(假设没有其他领域都贴)。

当你运行文章::创建($请求-&#62; all());在你没有复选框将基本上通过它的数据一个空集,这意味着你的数据库将被填充字段的默认值,你没有提供。

因为你没有提供你的迁移默认,MySQL会猜默认应该是基于字段类型,这在一个布尔值,则。你可能会看到一些警告/错误虽然。

有方法可以让这使工作负荷当保存一个复选框或当它不在。在这样的情况下最简单的方法就是将每个复选框的值为明确地建立在你的迁移,即默认值

迁移:

为表-&#62;布尔“图标”)-&#62;默认);

形式:

{!!形式::复选框“标题”“1”);!!}

这样,当标题复选框,你在request→(美元)返回一个数组包含一个项目'title' => '1'这是保存在你的数据库。所有的箱子都unticked拖欠0按您的迁移。

我喜欢但是更加明确,当我写我的处理存储方法。

$第=文章();$第-&#62;头衔=要求美元-&#62;“标题”);//将设置为第—&#62;标题真/假根据是否存在在你输入标题/ /…$第-&#62;保存();

你记得要把他们在可美元阵列中的“第一个模型吗?

受保护的可美元=“图标”“标题”图像优化];

作为一个旁注的复选框的东西。你可以用相同的名字做一个隐藏的输入,并使其虚假。这样,如果复选框被选中,这将是错误的,但如果它被选中,它将返回true,这是最后的价值:

<div=“输入wrpr”&#62;{!!::标签(标题、页面标题”)!{!}!!形式::隐藏(标题,假);!{!}!!::复选框(标题,“价值”);!!}</div>

您可以检查复选框设置isset($请求-&#62;图标)空($请求-&#62;图标)&#62;(图标)

公共功能商店createarticlerequest要求美元{foreach([“图标”“标题”图像优化]作为合箱{要求美元合箱=要求美元-&#62;合箱);}文章::创造要求美元-&#62;全部());退货重定向&#39;文章&#39;);}

你可以在Laravel使用修改器。使用此链接,你就明白了:—

https:/ / / / / /文档laravel.com 5.3 eloquent - mutators

来自  https://stackoverflow.com/questions/41070382/how-to-save-boolean-values-in-laravel-eloquent




普通分类: