Neil Young
Neil Young

Reputation: 556

Laravel 5 not storing checkbox value

We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value.

We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a field even though we are adding it as a field in the migration file.

Any help on this would be appreciated.

Mirgration File:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->date('dob');
        $table->boolean('optin')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

Then we add it to the register.blade.php file:

<div class="form-group">
                        <label class="col-md-4 control-label">Optin</label>
                        <div class="col-md-6">
                            <input type="checkbox" class="form-control" name="optin">
                        </div>
                    </div>

At the point of creating the User model, we check the value of the checkbox and assign it.

protected function create(array $data)
{

    //this does return 1 or 0 as expected
    $optin = ($data["optin"] == "on") ? 1 : 0; 

    return User::create([
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'dob' => $data['dob'],
        'optin' => $optin
    ]);
}

But at this point the field is null. No value is entered into the database...

Upvotes: 0

Views: 2084

Answers (2)

fahad.hasan
fahad.hasan

Reputation: 912

Have you put the field 'optin' in the $fillable array within the model? Otherwise you cant create a User with 'optin' using the static create method.

//File: User.php
protected $fillable = ['optin'];

Upvotes: 2

pespantelis
pespantelis

Reputation: 15382

The model already has a static create() function. Therefore, when you make a call like User::create($data) from your controller, your function is not called.

My approach is to change the name of your function and make it static.

Update

Also you can override the create function:

public static function create(array $attributes)
{
    $attributes["optin"] = ($attributes["optin"] == "on") ? 1 : 0;

    return parent::create($attributes);
}

Upvotes: 0

Related Questions