LoginSignup
0
0

More than 3 years have passed since last update.

Field ' ' doesn't have a default value

Posted at

Laravelの画像投稿機能実装時のエラー

画像投稿機能実装中に以下のエラーが表示された

Field 'user_id' doesn't have a default value

問題点1
posts controller storeアクション

 public function store(Request $request){
    $validator = Validator::make($request->all(), [
        'file' => 'required|max:10240|mimes:jpeg,gif,png',
        'content' => 'required|max:191'
    ]);

    if($validator->fails()){
        return back()->withInput()->withErrors($validator);
    }

    $file = $request->file('file');
    $path = Storage::disk('s3')->putFile('/', $file, 'public');

    Post::create([
        'user_id' => \Auth::user()->id,
        'image_file_name' => $path,
        'content' => $request->content
    ]);

     return redirect('/');
}

'user_id' => \Auth::user()->id,の一文が抜けていた

問題点2
Post Model Post.php

class Post extends Model
{
    protected $fillable =[
        'image_file_name', 'content', 'user_id'
    ];
}

$fillableの中に 'user_id' を記入していなかったため。

以上の2点を解決後フォームから送信で無事に動作した。
マイグレーションファイルにuser_idと書いていたのに上記のファイル無いで設定していないために発生したエラーだった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0