I have a views table in the database and i'm trying to update a record in it ( or create it if it doesn't exist yet) with this code:
$ar = ['number_of_views' => $number_of_views['number_of_views']+1, 'post_id' => $post->id];
App\View::updateOrCreate(['id' => $number_of_views['id']], $ar);
Unfortunately this returns an error:
SQLSTATE[HY000]: General error: 1364 Field 'post_id' doesn't have a default value (SQL: insert into
views
(number_of_views
,updated_at
,created_at
) values (1, 2017-02-09 14:41:19, 2017-02-09 14:41:19))
It seems that it isn't recognizing the 'post_id' => $post->id
hence returning an error as if it wasn't set at all.
This error only appears if the record is to be created and not if it already exists.
You need to add the
post_id
field to the fillable attribute on the model for mass assignment like this: