CodeConnoisseur
CodeConnoisseur

Reputation: 1869

How to solve integrity constraint violation in Laravel 5.7?

I am getting the following error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into answers (body, user_id, question_id, updated_at, created_at)

I am trying to submit an answer to a form using Laravel and I am getting the above error. First I checked my schema in my answers table and the user_id is correctly defined:

public function up()
{
    Schema::create('answers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('question_id');
        $table->unsignedInteger('user_id');
        $table->text('body');
        $table->integer('votes_count')->default(0);
        $table->timestamps();
    });
}

Next I added this code to my AnswersController.php to validate the code and redirect once the answer is submitted:

public function store(Question $question, Request $request)
{    
    $request->validate([
        'body' => 'required'
    ]);

    $question->answers()->create(['body' => $request->body, 'user_id' => \Auth::id()]);

    return back()->with('success', "Your answer has been submitted successfully");
}

I imported the Answer class into my AnswersController.php and I also made the body and user_id fields into fillable in the Answer.php model:

protected $fillable = ['body', 'user_id'];

When I click the submit button on my form, I get the SQL State error shown above. user_id is a valid field in my DB answers table. I can't seem to figure it out.

Upvotes: 0

Views: 435

Answers (1)

Watercayman
Watercayman

Reputation: 8178

Your code looks fine. But the error is pretty straightforward: you are not getting a user_id. IE you are trying to create an answer pivot, calling user_id to be created from a non-object. \Auth::id() is empty or not recognized for what you want. Call the user object instead.

Try this:

$question->answers()->create(['body' => $request->body, 'user_id' => \Auth::user()->id]);

Also make sure you actually have a user: send the form back through a route with the auth middleware:

Route::group(['middleware' => ['auth']], function () {
   Route::resource('questions.answers', 'AnswersController');
   // Any other routes where you want a user
}

Upvotes: 2

Related Questions