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

1 messages · Page 1 of 1 (latest)

vapid cave
#

So I'm following Laracast's Laravel guide, and I did the exact same thing as he did in the video.

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('category_id');
            $table->string('slug')->unique();
            $table->string('title');
            $table->text('excerpt');
            $table->text('body');
            $table->timestamps();
            $table->timestamp('published_at')->nullable();
        });

But when I do

Post::create([                                                            'title' => 'My Family Post',                                                'excerpt' => 'Excerpt for my post',                                         'body' => 'Lorem ipsum dolar sit amet.',                                    'slug' => 'my-family-post',                                                 'category_id' => 1                                                          ]);

I get an error Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (Connection: mysql, SQL: insert intoposts (title, excerpt, body, slug, updated_at, created_at) values (My Family Post, Excerpt for my post, Lorem ipsum dolar sit amet., my-family-post, 2024-03-02 01:41:29, 2024-03-02 01:41:29)).
What should I do?

blazing bough
#

Hi @vapid cave, I hope this message finds you good
Eloquent models are protected against mass assignment vulnerabilities by default so you need to specify either a fillable or guarded property on your Post model class

protected $fillable = ['category_id', 'slug', 'title', 'excerpt', 'body'];

weary remnant
#

Hi. check category_id field in database if you set default value