How to save boolean values in laravel eloquent

75,054

Solution 1

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

Solution 2

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>

Solution 3

With VUE you can do it like this:

Add this line to your table

$table->boolean("image-optimization")->default(0);

Add this to your model, it will modify the value inserted in the database

protected $casts = ['image-optimization' => 'boolean'];

You don't have to modify the request with this method

Docs: https://laravel.com/docs/8.x/eloquent-mutators

Solution 4

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');
}
Share:
75,054

Related videos on Youtube

Alexander Solonik
Author by

Alexander Solonik

GORMENT

Updated on July 09, 2022

Comments

  • Alexander Solonik
    Alexander Solonik almost 2 years

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

  • Chris
    Chris over 4 years
    Nice solution! Thanks a lot.