Search code examples
laravelsqliteerror-handlingcrudnullable

Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed


I'm new to laravel, trying to store the data but kept getting this error:

   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))

store method in controller:

   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');
    }

store request:

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

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

database:

 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();
    });
}

the error is pointing to the controller:

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

But not sure what's the fix. Please help. Thanks in advance.


Solution

  • Make the user_id column a foreign key that references the id column on the users table, and make it nullable if a Course doesn't have to be assigned a user

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

    You would also want to change the index, since it might be null

    $table->index('user_id');

    Otherwise

    • require a user to be logged in so a Course can be created
    public function authorize()
    {
      return auth()->check();
    }
    
    • add the auth()->id() to the validated request data
    $course = $request->validated();
    $course['user_id'] = auth()->id();
    $addCourse = Course::create($request->all());