esorone's avatar

Save toggle data into db

Goodnight,

I'm struggling with saving my toggle data into the database.

I tried numerous options, but no did work

current try. In my view:

                               {{ Form::checkbox('feedbackboolean', 1) }}Ja
                               {{ Form::checkbox('feedbackboolean', 0) }}Nee

Seconds Try: Just a toggle button

<input type="checkbox" name="feedbackboolean" checked data-toggle="toggle" data-on="1" data-off="0">

In my controller:

        $post->feedbackboolean = $request->get('feedbackboolean');

or 

      $post->kennisbankboolean = $request->get('kennisbankboolean', 0);

Or

        $post->feedbackboolean = $request->feedbackboolean;

But unfortunately they did not work. The samples above , are just a sample which I all found online. So somewhere Im misinterpret the solution

The rest of the post form is stored in the database and works as it should be.

What am I missing here.

As always, thanks in advanced.

0 likes
24 replies
Cronix's avatar
{{ Form::checkbox('feedbackboolean', 1) }}Ja
// or
<input type="checkbox" name="feedbackboolean">
$post->feedbackboolean = (int) $request->has('feedbackboolean');

The actual value doesn't matter. I just check whether it was present in the request with has() (which returns a boolean) and then cast that to an int. This works very well with 0/1 values.

So if it was checked, it will be in the request, and become a 1. If it wasn't checked, it won't be in the request and will become a 0.

esorone's avatar

Hey Cronix,

As always, thanks again. I'm able to store a value, but..

Still one question left. If I check it or don't check it, the value is the same "0" in the database.

Any ideas left?

View:

                    <div class="control-group">
                            <label class="control-label">{{ Form::label('kennisbankboolean', 'Beschikbaar in Kennisbank?') }}</label>
                            <div class="controls">         

                               {{Form::checkbox('kennisbankboolean', 1)}}Ja
                               <hr>
                               <label class="control-label">{{ Form::label('title', 'Wil je feedback geven?') }}</label>
                               {{ Form::checkbox('feedbackboolean',1) }}Ja
                                <hr>
                               <label class="control-label"> {{ Form::label('Feedbacktxt', 'Feedback') }}</label>
                                <div class="controls">
                                {{ Form::textarea('feedbacktxt', null, array('class' => 'span11')) }}
                                <hr>
                            </div>
                        </div>
                    </div>

Controller:

    public function store(Request $request)
    {
        //Validating
       $this->validate($request, [
            'title' => 'required|max:100',
            'channel' => 'required',
            'department' => 'required',
            'hoofdcategory' => 'required',
            'subcategory' => 'required',
            'body' => 'required',
            'user_id' => 'required',
            'starttijd' => 'required',
        ]);


        $startTime = Carbon::parse($request->starttijd);
        $finishTime = Carbon::now();
        $totalDuration = $finishTime->diffinSeconds($startTime);
        $seconden = $request->starttijd;
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->channel_id = $request->channel;
        $post->department_id = $request->department;
        $post->hoofdcategories_id = $request->hoofdcategory;
        $post->subcategories_id = $request->subcategory;
        $post->kennisbankboolean = (int) $request->has('kennisbankboolean');
        $post->feedbackboolean = (int) $request->has('feedbackboolean');
        $post->feedbacktxt = $request->feedbacktxt;
        $post->user_id = $request->user_id;
        $post->seconds = $totalDuration;

        if ($post->save()){
            return redirect()->route('posts.index')
            ->with('flash_message_success', 'Contact,
             ' . $post->title . ' Geregistreerd');
        }else {
            return redirect()->route('posts.index')
            ->with('flash_message_error', 'Contact,
             ' . $post->title . ' NIET Geregistreerd');
        }
        

        //Display a successful message upon save



    }
Snapey's avatar

Is your database table column exactly called kennisbankboolean ?

Cronix's avatar

It looks ok, so I guess same question as Snapey.

I'm also not sure why you need to have a feedbackboolean column at all. If there is feedback, the feedbacktxt field in the db won't be null.

esorone's avatar

Hey Both,

Yes, my column is called "kennisbankboolean" and "feedbackboolean". And there is a 0 value stored in the db. I just copy / past the name from sequel Pro to my code editor (just to make sure)

The feedbackboolean service an different purpose. If this one is checked, the feedback is related to a knowledge base. The Feedback field is generic.

I hope you guys got some ideas left. Or maybe a different approach?

esorone's avatar

Update.

I just checked the value via js.

<script>
    $(document).ready(function () {
        $('input[name="kennisbankboolean"]').change(function(){ 
        console.log($('.controls').find("input:checkbox[name ='kennisbankboolean']:checked").val());
});
});
</script>

If I check the checkbox, the value is shown as 0 If I uncheck it, i receive "undefined"..

I tried to update the $post with;

      $post->kennisbankboolean = (int) $request->has('kennisbankboolean')? 1 : 0;

Or the other way around, but still no luck.

I would expect a 1 when checked and a 0 unchecked.

Cronix's avatar

The value being sent has nothing to do with it.

This is basic html. If a checkbox is checked, the name and value of the checkbox get submitted in the request. If a checkbox is not checked, it is NOT sent in the request. This has nothing to do with php, javascript or anything else. This is how html forms work for 30 years now.

Of course your javascript is coming up as undefined. The logic in it is flawed. You unchecked it, so find("input:checkbox[name ='kennisbankboolean']:checked") doesn't exist since it's not checked, but you're looking for where it IS checked.

Try a simple example. Put this on your form (don't use that dumb form library)

<input type="checkbox" name="testcb" value="1">Test Checkbox

in the controller, do

public function store(Request $request)
{
    return (int) $request->has('testcb');
    // rest of your code below...doesn't matter for this test
}

Now check the checkbox and submit. You should see a 1. Do the same thing with the checkbox unchecked. You should see a 0.

esorone's avatar

Hey Cronix,

I know, the behaviour is at least 30 years, but I cannot solve this one, and my current technique is trail and error.. And read numerous topics online and just try and give some extra input.

You will not believe it, but your solution provides a 0, same as before.

I updated mine:

view
<input type="checkbox" name="kennisbankboolean" value="1">

controller
    $post->kennisbankboolean = (int) $request->has('kennisbankboolean');

I even added your field to my database, contoller, etc

view

<input type="checkbox" name="testcb" value="1">

Controller:
        $post->testcb = (int) $request->has('testcb');

And again only a Zero :-(

What am I missing here........

[Quote] Try a simple example. Put this on your form (don't use that dumb form library) [Unquote]

Done

Cronix's avatar

Do you have anything else interfering with the request, like javascript? I do this all of the time with no issues.

esorone's avatar

In the same form I have a "dynamic" cascading pulldown menu. Category and subcategory. I just removed the script, but same result :-(

This one is really giving me an headache

esorone's avatar

What I'm going to do, is create a new page tomorrow, Fresh start, and lets see if I'm able to store the proper values.

Keep you guys posted.

Snapey's avatar

dd the actual request data what does your controller recieve?

dd($request->all());
Snapey's avatar

and for your sanity, just hardcode 1 in the controller and check its saved

esorone's avatar

Hey Snapey,

I did not see any value during the DD.. $post->kennisbankboolean = (int) $request->has('kennisbankboolean'); $post->feedbackboolean = (int) $request->has('feedbackboolean');

Did not check anything.

array:10 [▼
  "_token" => "iYzAPfAzpyXHsAZVHih2Pn63axcJ"
  "title" => "fasdfasdf"
  "channel" => "1"
  "department" => "2"
  "hoofdcategory" => "1"
  "subcategory" => "3"
  "user_id" => "1"
  "starttijd" => "2018-09-18 19:18:29"
  "body" => "fasdfasdfasd"
  "feedbacktxt" => "00"
]

Checked both checkboxes.

array:10 [▼
  "_token" => "iYzAPfAzpyXHsAZVHih2Pn63axcJiFZ"
  "title" => "fasdfasdf"
  "channel" => "1"
  "department" => "2"
  "hoofdcategory" => "1"
  "subcategory" => "3"
  "user_id" => "1"
  "starttijd" => "2018-09-18 19:19:49"
  "body" => "fasdfasdfasd"
  "feedbacktxt" => "11"
]

I'm still able to store a 0 value.. the other value is null... Im really confused.

Cronix's avatar

Something is wrong with your form then if they don't show up in the request and they were checked. Show the whole form, including opening/closing form tags. Also, any javascript that is on this page.

ultimateBusiness's avatar

Please, add to your validation the following rules:

'kennisbankboolean' => 'nullable',
'feedbackboolean' => 'nullable'

so the values can came through the validation and didn't cut off from the request.

Snapey's avatar

are you still using the form library? make sure you name the checkboxes

esorone's avatar

Hello Both,

Sorry for the delay, (Busy at work).

First of all, really appreciate you help on the topic..

@ultimateBusiness I tried your solution, but it dit not solve my issue

Underneath my view.


@extends('layouts.adminlayouts.admin_design') @section('content')@can('Contacten Registreren')
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<div id="content">

    <div id="content-header">
        <div id="breadcrumb">
            <a href="index.html" title="Go to Home" class="tip-bottom">
                <i class="icon-home"></i> Home</a>
            <a href="{{url('/posts/')}}">Registraties</a>
            <a href="{{ route('posts.create') }}" class="current">Registratie aanmaken</a>
        </div>
        <h1>Registreer een klantcontact</h1>
    </div>
    @if(Session::has('flash_message_success'))
    <button data-dismiss="alert" type="button" class="close" <i class="icon-sitemap">
        </i>
    </button>
    <div class="alert alert-success">
        <em> {!! session('flash_message_success') !!}</em>
    </div>
    @endif @if(Session::has('flash_message_error'))

    <button data-dismiss="alert" type="button" class="close" <i class="icon-sitemap">
        </i>
    </button>
    <div class="alert alert-danger">
        <em> {!! session('flash_message_error') !!}
                @foreach ($errors->all() as $error)
                  {!! $errors->first() !!}
                @endforeach
        </em>
    </div>
    @endif
            @if(Session::has('errors'))
    <button data-dismiss="alert" type="button" class="close" <i class="icon-sitemap">
        </i>
    </button>

    <div class="alert alert-danger">
        <em> 
    @foreach ($errors->all() as $error)
       {!! $errors->first() !!}
    @endforeach
        </em>
    </div>
@endif


    <div class="container-fluid">
        <hr>
        <div class="row-fluid">
            <div class="span8">
                <div class="widget-box">
                    <div class="widget-title">
                        <span class="icon">
                            <i class="icon-lemon">
                            </i>
                        </span>
                        <h5>Registreer klantcontact</h5>
                    </div>
                    <div class="widget-content nopadding">
                        {{ Form::open(array('route' => 'posts.store', 'class' => 'form-horizontal', 'id'=>'tijd')) }} @csrf
                        <div class="control-group">
                            <label class="control-label">{{ Form::label('title', 'Title') }}</label>
                            <div class="controls">
                                {{ Form::text('title', null, array('class' => 'span11')) }}
                            </div>
                        </div>
                        {{ Form::open(array('url'=>'','files'=>true)) }}
                        <div class="control-group">
                        <label class="control-label">Kanaal</label>
                            <div class="controls">
                                <select name="channel" id="channel">
                                    @foreach($channels as $channel)
                                    <option value="{{$channel->id}}">{{$channel->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        <label class="control-label">Afdeling</label>
                            <div class="controls">
                                <select name="department" id="department">
                                    @foreach($departments as $department)
                                    <option value="{{$department->id}}">{{$department->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <label class="control-label">Hoofd Categorie</label>
                            <div class="controls">
                                <select name="hoofdcategory" id="hoofdcategory">
                                <option selected disabled>Selecteer een hoofdcategorie</option>
                                    @foreach($categories as $category)
                                    <option value="{{$category->id}}">{{$category->name}}</option>    
                                    @endforeach
                                </select>
                            </div>
                            <label class="control-label">Sub Categorie</label>
                            <div class="controls">
                                <select class="form-control" name="subcategory" id="subcategory">
                                <option selected="selected"></option> </select>
                                    <input type="hidden" name="user_id" id="user_id" value="{{Auth::user()->id}}">
                            </div>
                            <div class="control-group">
                            <label class="control-label">Tijdstip: </label>
                            <div class="controls">
                                    <input type="text" name="starttijd" id="starttijd" class="span11" value="{{ \Carbon\Carbon::now() }} " />
                            </div>
                        </div>
                                     </div>
                        <div class="control-group">
                            <label class="control-label"> {{ Form::label('body', 'Body') }}</label>
                            <div class="controls">
                                {{ Form::textarea('body', null, array('class' => 'span11')) }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="span4">
            <div class="widget-box">
            <div class="widget-title">
                        <span class="icon">
                            <i class="icon-edit">
                            </i>
                        </span>
                        <h5>Feedback</h5>
                    </div>
                    <div class="widget-content">
                    <div class="control-group">
                            <label class="control-label">{{ Form::label('kennisbankboolean', 'Beschikbaar in Kennisbank?') }}</label>
                            <div class="controls">         
                             <input type="checkbox" name="kennisbankboolean" value="1">
                            <BR>
                               <hr>
                               <label class="control-label">{{ Form::label('title', 'Wil je feedback geven?') }}</label>
                                {{ Form::checkbox('feedbackboolean', 1) }}Ja
                                <hr>
                               <label class="control-label"> {{ Form::label('Feedbacktxt', 'Feedback') }}</label>
                                <div class="controls">
                                {{ Form::textarea('feedbacktxt', null, array('class' => 'span11')) }}
                                <hr>
                            </div>
                        </div>
                    </div>
            </div>                       {{ Form::submit('creer contact', array('class' => 'btn btn-success btn-lg btn-block')) }}  {{ Form::close() }}
          </div>
        </div>
    </div>
</div>
@endcan
    <script>
    $(document).ready(function () {
        $("#hoofdcategory").on('change', function (e) {
            console.log(e);
            var cat_id = e.target.value;

            $.get('/admin/ajax-subcat/' + cat_id, function (data) {
                //success data
                // console.log(data);
                $('#subcategory').empty();
                $.each(data, function (index, subcatObj) {
                    $('#subcategory').append('<option value ="' + subcatObj.id + '">' +
                        subcatObj.name + '</option>');

                });
            });
        });
    });
</script>

@endsection

My Controller:

 /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //Validating title and body field
       $this->validate($request, [
            'title' => 'required|max:100',
            'channel' => 'required',
            'department' => 'required',
            'hoofdcategory' => 'required',
            'subcategory' => 'required',
            'body' => 'required',
            'user_id' => 'required',
            'starttijd' => 'required',
        ]);


        $startTime = Carbon::parse($request->starttijd);
        $finishTime = Carbon::now();
        $totalDuration = $finishTime->diffinSeconds($startTime);
        $seconden = $request->starttijd;
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->channel_id = $request->channel;
        $post->department_id = $request->department;
        $post->hoofdcategories_id = $request->hoofdcategory;
        $post->subcategories_id = $request->subcategory;
        $post->kennisbankboolean = (int) $request->has('kennisbankboolean');
        $post->feedbackboolean = (int) $request->has('feedbackboolean');
        $post->feedbacktxt = $request->feedbacktxt;
        $post->user_id = $request->user_id;
        $post->seconds = $totalDuration;

        // dd($request->all());
        if ($post->save()){
            return redirect()->route('posts.index')
            ->with('flash_message_success', 'Contact,
             ' . $post->title . ' Geregistreerd');
        }else {
            return redirect()->route('posts.index')
            ->with('flash_message_error', 'Contact,
             ' . $post->title . ' NIET Geregistreerd');
        }
        

    }

JS script route:

Route::get('admin/ajax-subcat/{cat_id}', 'CascadeController@ajax')->name('ajax');

So the CascadeController

<?php

namespace App\Http\Controllers;

use App\Subcategory;

/**
 * 
 */
class CascadeController extends Controller
{
    public function ajax($cat_id)
    {
        $cat_id = $cat_id;
        $subcategory = Subcategory::where('category_id', '=', $cat_id)->get();
        return response()->json($subcategory);
    }
}

Cronix's avatar

You have an invalid form. You have 2 form open tags, and 1 form close tag. You can't have a form withing a form.

{ Form::open(array('route' => 'posts.store', 'class' => 'form-horizontal', 'id'=>'tijd')) }}
//...
{{ Form::open(array('url'=>'','files'=>true)) }}
//...
{{ Form::close() }}

remove the 2nd form open tag.

esorone's avatar

Hello,

Really sharp.. I check this x times, but did not notice this one.

So I removed it..

BUT, it did not solve my problem :-(.

I just checked the checkbox both Times (checked / unchecked), both ways stores a zero in the database.

A dd($request->all()); still produces:

array:10 [▼
  "_token" => "ar52eQBH5LXFR49xO1S"
  "title" => "sdfasdf"
  "channel" => "2"
  "department" => "5"
  "hoofdcategory" => "2"
  "subcategory" => "2"
  "user_id" => "1"
  "starttijd" => "2018-09-19 19:03:18"
  "body" => "sadfasdfasdfasdf"
  "feedbacktxt" => "00"
]
Cronix's avatar

What does this library do?

<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

Try removing it.

esorone's avatar

Hey Both,

I just started a new view (result), (complete new setup) and this works perfectly fine. So I have made an error somewhere. Therefor I will build this page from scratch.

For other members, the following works, AND I will show my errors later on.

VIEW

<div class="span4">
    <div class="widget-box">
        <div class="widget-title">
            <span class="icon">
                <i class="icon-edit">
                </i>
            </span>
            <h5>Feedback</h5>
        </div>
        <div class="widget-content">
            <div class="control-group">
            {{ Form::open(array('route' => 'result.store', 'class' => 'form-horizontal', 'id'=>'tijd')) }} @csrf

            <input type="checkbox" name="kennisbankboolean" value="1">

             {{ Form::submit('creer contact', array('class' => 'btn btn-success btn-lg btn-block')) }}  {{ Form::close() }}
        
        </div>
        </div>
    </div>
</div>

Controller

  /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $result = new Result();
        $result->name = 'testName';
        $result->kennisbankboolean = (int) $request->has('kennisbankboolean');

        if ($result->save()){
            return redirect()->route('result.index')
            ->with('flash_message_success', 'Contact,
             ' . $result->name . ' Geregistreerd');
        }else {
            return redirect()->route('result.index')
            ->with('flash_message_error', 'Contact,
             ' . $result->name . ' NIET Geregistreerd');
        }
    }

Unchecked will store a 0, and checked will store a 1

Cronix's avatar
Cronix
Best Answer
Level 67

Yes, it will work it's what I've been saying lol. The problem is your form, or something interfering with it, before it even gets to laravel (or else the checkbox would come through in the $request object when checked).

I'd really urge you to use actual html for your forms, and not to use that form library. Your IDE will alert you if you do things like have 2 open form tags (or any mismatched tags in general), but it won't with that form library.

1 like
esorone's avatar

Hey Both,

I just made an identical form, based on copy / past of the original form. I tested it with the Formbuilder as well as HTML. I tested it one by one, so add a new field, test it, add another one, etc.

I did not find any errors in my new form and I used the same controller.

So there is something strange in my code and the form library..

I wish I could point it out, but I can't, but my problem is solved.

Thanks again for helping me and the thorough checks of my code.

Kr

Please or to participate in this conversation.