SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`post`) values (こんにちは))と出る
解決したいこと
投稿サイトを作っています。
フォームに『こんにちは』と入力し投稿ボタンを押すと、
『SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into posts
(post
) values (こんにちは))
』
と出てきてしまいます。
経緯としては、
以前はカラムを『$table->integer('user_id')->default(1);』としておりましたが、ユーザーID2で投稿しても、ユーザーID1の投稿として投稿されてしまうため、『->default(1)』を抜くと出てきてしまいます。
postテーブル
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->integer('id')->autoIncrement();
$table->integer('user_id');
$table->string('post',400)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
##usersテーブル
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->autoIncrement();
$table->string('username',255);
$table->string('mail',255);
$table->string('password',255);
$table->string('bio',400)->nullable();
$table->string('image')->default('/storage/dawn.png');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->rememberToken();
});
}
コントローラー
//新規投稿画面
public function createForm(Request $request)
{
$post = $request->input('newPost');
\DB::table('posts')->insert([
'post' => $post,
]);
return redirect('top');
}
//投稿更新
public function postsupdate(Request $request, Post $post)
{
$edit = Post::find($id);
$edit->post = $request->input('post');
Post::query()
->where('id', $id)
->update(
['post' => $post]
);
return back();
}
自分で試したこと
・『->default(1)』を抜き、"php artisan cache:clear","php artisan config:cache","php artisan migrate:fresh","php artisan cache:refresh","php artisan db:seed;"を実行。
・https://qiita.com/tewi_r/items/58af980c258a484cec65 を参考に'strict' => falseへ変更する。