Laravel 5.4 field has no default value

I have this error, and not one of the results that I checked Google looks like my problem.

I have an application with class Deal, User and Matches

The deal has a lot of matches. The user has many matches. The user has many transactions.

I am trying to create a new match using the Deals object

$deal->matches()->create(['user_id'=>$id]);

This is my compliance class, I defined all the necessary relationships

class Match extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    public $timestamps = false;
    public $expired_on = "";


    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->matched_on = $model->freshTimestamp();
        });
    }

    public function __construct(){
        $d = (new \DateTime($this->matched_on))->modify('+1 day');
        $this->expired_on = $d->format('Y-m-d H:i:s');
    }


    /**
     * Get the user that owns the match.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * Get the deal that owns the match.
     */
    public function deal()
    {
        return $this->belongsTo('App\Deal');
    }
}

And I keep getting this error when I try to create a new match.

QueryException in line Connection.php 647: SQLSTATE [HY000]: General error: 1364 Field 'user_id' has no default value (SQL: insert into matches( deal_id) values ​​(1))

I want me to be an empty array, what could be the problem?

+12
5

guarded fillable :

protected $fillable = ['user_id', 'deal_id'];
+28

,

/database.php

'strict' => false .

+16

.

, , , , Match .

            $match->user_id = $id;
            $match->deal_id = $deal->id;
            $match->matched_on = $match->freshTimestamp();
            $match->save();
+3

For me, creating a nullable field solved this problem.

eg

$table->string('user_id')->nullable();

... and restarting migrations.

0
source

Since this was a unique field in my case, I could not make it nullable.

For me, I had an empty constructor that was causing the problem, I don’t know why. Please comment if anyone knows the reason.

public function __construct(){

}

Commenting / deleting this solved the problem.

0
source

Source: https://habr.com/ru/post/1016274/


All Articles