1

I followed a laracast series and stuck at some point.

I got the following error message by trying to submit a blog post:

QueryException in Connection.php line 713: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (codeshare.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into articles (title, body, published_at, updated_at, created_at) values (lorem, ipsum, 2016-07-19 10:11:49, 2016-07-19 10:11:49, 2016-07-19 10:11:49))

The strange thing is, that the submitted article is stored to the DB and also appears in my articles view.

ArticlesController:

public function store(ArticleRequest $request) {
Auth::user()->articles()->save(new article($request->all()));
Article::create($request->all());
return redirect('articles');
}

Article Model:

public function user() {
$this->belongsTo('App\User'); //user_id
}

Schema:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->text('body');
        $table->timestamp('created_at');
        $table->timestamp('published_at');

        $table->foreign('user_id')
              ->references('id')
              ->on('users')
              ->onDelete('cascade');

    });
}

Any idea what's the reason for the exception?

Krishna Mohan
  • 1,503
  • 3
  • 22
  • 28
Steve Brown
  • 427
  • 1
  • 6
  • 16

1 Answers1

1

You can try to leave out this line

Article::create($request->all());

since you are already saving the article with

Auth::user()->articles()->save(new Article($request->all()));
piscator
  • 8,028
  • 5
  • 23
  • 32
  • You're welcome @SteveBrown! Please consider to accept this answer (and previous answers to your questions) by clicking the check-mark, when it solved your question. It's no obligation, but it can indicate to other users that the answers have been helpful and give some reputation to you and the answerers. Cheers! – piscator Jul 19 '16 at 12:57