0

I created a simple form that sends some data to a mysql database. When entering name or email everything workes fine. Except for the checkboxes. It runs perfekt when all checkboxes are checked, but if not -> i always get this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'checkbox1' cannot be null

so i got this for creating the form:

{{Form::label('checkboxlabel', 'Agree')}}
{{Form::checkbox('checkbox1',1, true)}}

This is my migration file:

 Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('email')->unique();
        $table->boolean('checkbox1')->nullable();

And this my Controller file:

    $user = new User;
    $user->email= $request->input('email');
    $user->checkbox1= $request->input('checkbox1');

Any help on this? Just want some true or false value for checked or not checked. Thx guys!

1
  • Can you paste the whole controller? This is just a snippet Commented Nov 9, 2017 at 15:56

2 Answers 2

1

There is something weird going on but based on your question, I don't think it matters...

The way checkboxes work, if they aren't checked, then nothing gets sent to the server. As such, using your current code, the checkbox1 field will always either be true or null, it will never be false because false is never going to be sent to the server as a value.

What you likely need to do is apply a default when inserting...

$user->checkbox1= $request->input('checkbox1', 0);

This way if the checkbox isn't checked, your code will assume false and insert it into the database as such.

Now for the weird thing that's going on, your error message indicates you can't insert null into that column but you've very clearly set that field to nullable in your migration. Are these the same fields? Did you possibly update the migration without re-running it to update the schema in your database?

Can you run the statement show create table users and update your question with the contents of whatever is returned from that query?

Sign up to request clarification or add additional context in comments.

2 Comments

You could use $request->has('checkbox1'); to get a bool.
Thx guys, this worked! Refreshed and started the migration again!
0

If you do not explicitly need a null value for a boolean you can do:

// Inside your migration
$table->boolean('checkbox1')->default(false);

// Inside the controller
$user->checkbox1 = $request->input('checkbox1');

Alternatively you can set a default if the value is not set in the request:

// Inside your migration
$table->boolean('checkbox1');

// Inside the controller
$user->checkbox1 = $request->input('checkbox1', 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.