Illuminate \ Database \ QueryException SQLSTATE [23000]:违反完整性约束:19 NOT NULL约束失败

时间:2020-06-06 23:20:59

标签: laravel sqlite error-handling crud nullable

我是laravel的新手,试图存储数据,但始终收到此错误:

   Illuminate\Database\QueryException
   SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: courses.user_id (SQL: insert into "courses" ("title", "image" "updated_at", "created_at") values (new title, ?, 2020-06-06 23:02:53, 2020-06-06 23:02:53))

在控制器中存储方法:

   public function store(StoreCourseRequest $request) {
      $addCourse = Course::create($request->all());

       foreach ($request->input('course_images', []) as $file) {
          $addCourse->addMedia(storage_path('tmp/uploads/' . $file))->toMediaCollection('course_images');
          }

      if ($media = $request->input('ck-media', false)) {
          Media::whereIn('id', $media)->update(['model_id' => $addCourse->id]);
          }
      return redirect('/course');
    }

存储请求:

   class StoreCourseRequest extends FormRequest
     {
     public function authorize()
      {
         return true;
      }

    public function rules()
     {
       return [
          'title'       => [
              'required',
           ], 
      ];
     }
 }

数据库:

 Schema::create('courses', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->string('title');
        $table->string('image')->nullable();
        $table->timestamps();
        $table->index('user_id');
        $table->softDeletes();
    });
}

错误指向控制器:

   $addCourse = Course::create($request->all());

但不确定如何解决。请帮忙。提前致谢。

1 个答案:

答案 0 :(得分:0)

user_id列用作引用用户表上id列的外键,并在不必为课程分配用户的情况下将其设置为空

$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');

您还希望更改索引,因为它可能为空

$ table-> index('user_id');

否则

  • 要求用户登录才能创建课程
public function authorize()
{
  return auth()->check();
}
  • auth()->id()添加到已验证的请求数据中
$course = $request->validated();
$course['user_id'] = auth()->id();
$addCourse = Course::create($request->all());