Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 field doesn't have a default value

I am having this error and none of the googled result i checked is similar to my problem.

I have an application with class Deal, User, and Matches

A deal has many matches. A user has many matches. A user has many deals.

I am attempting to create a new Match using my Deal object

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

This is my match class, i have defined all needed 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 attempt to create a new match.

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

I have my guarded to be an empty array, what could be the problem?

like image 650
John David Avatar asked Apr 03 '17 13:04

John David


2 Answers

Remove the guarded array and add the fillable instead:

protected $fillable = ['user_id', 'deal_id']; 
like image 147
Alexey Mezenin Avatar answered Sep 27 '22 21:09

Alexey Mezenin


If you would like to revert to previous behavior, update your

config/database.php

file and set 'strict' => false for your connection.

like image 21
grantDEV Avatar answered Sep 27 '22 21:09

grantDEV