Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLSTATE[HY000]: General error: 1364 Field 'contactId' doesn't have a default value

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!

like image 918
Wijnand Avatar asked Dec 18 '22 14:12

Wijnand


2 Answers

Make contactId $fillable in Customer model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $fillable = ['contactId'];
}
like image 193
Dilip Hirapara Avatar answered Dec 20 '22 18:12

Dilip Hirapara


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'];
}
like image 43
VIKAS KATARIYA Avatar answered Dec 20 '22 16:12

VIKAS KATARIYA