4
votes

On my model (Customer) I have one required parameter: $contactId.

On executing Customer::create(['contactId' => $contactId]) I receive the following error:

"message": "SQLSTATE[HY000]: General error: 1364 Field 'contactId' doesn't have a default value (SQL: insert into customers (updated_at, created_at) values (2019-12-10 12:33:46, 2019-12-10 12:33:46))"

The contactId field is nowhere to be found on in the insert statement. The value of contactId is set to 4, which corresponds to the correct value in the database through a FK.

The migration for the Customer table:


`Schema::create('customers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
            $table->bigInteger('contactId')->unsigned();
            $table->foreign('contactId', 'FK_customer_contactId_contact_id')
                ->references('id')
                ->on('contacts');
        });`

What's preventing Eloquent from creating the correct insert statement here? I've triple checked the spelling of contactId throughout the flow and in the database.

When I manually insert a row into customers, I have no issues retrieving the data and the contact-relation.

Thanks for your time!

3
Is $contactId a null value?Jeremy Harris
@JeremyHarris it's not nullable. It turns out I didn't fully understand the workings of $fillable. Dilip his answer is the correct solution.Wijnand

3 Answers

7
votes

Make contactId $fillable in Customer model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $fillable = ['contactId'];
}
3
votes

If you use create method to save data in to database so you must have to write this fillable property in your model

<?php

class Customer extends Model
{
    protected $fillable = ['contactId'];
}
1
votes

Make contactId $fillable in model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $fillable = ['contactId'];
}

or

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $guarded = [];
}