Annonym Annonym - 3 months ago 10
PHP Question

Laravel5: QueryException while writing data to related database table. Error: "Cannot add or update a child row: a foreign key constraint fails"

I just created a

categories
table and related it to
articles
table.

$table->foreign('category_id')->references('id')->on('categories');


I also created a category selection field with name 'category_id' in the 'Create Article' form. Now while trying to create a new article, after I hit the submit button, I get the following error:


QueryException in Connection.php line 725: SQLSTATE[23000]: Integrity
constraint violation: 1452 Cannot add or update a child row: a foreign
key constraint fails (
laratry
.
articles
, CONSTRAINT
articles_category_id_foreign
FOREIGN KEY (
category_id
) REFERENCES
categories
(
id
)) (SQL: insert into
articles
(
title
,
body
,
published_at
,
user_id
,
updated_at
,
created_at
) values (This is
a test article, This is yet another test article for trying to find
what the error is., 2016-08-15 16:11:53, 1, 2016-08-15 16:11:53,
2016-08-15 16:11:53))


If I print_r( $request->all() ),

Array (
[_token] => E4fWVTpf2T5y23uOnaA0EK1hHyi2hYvkJZa99V3G
[title] => This is a test article
[body] => This is yet another test article for trying to find what the error is.
[category_id] => 1
[published_at] => 2016-08-15
[tag_list] => Array ( [0] => 1 )
)


My Controller's store method for article:

class ArticlesController extends Controller
{
public function store(Request $request)
{
Auth::user()->articles()->create($request->all());
flash()->success('Your article has been created.');
return redirect('articles');
}
}


My Models:

class Article extends Model
{
protected $fillable = ['title','body','published_at','user_id'];

protected $dates = ['published_at','created_at'];

public function category()
{
return $this->belongsTo('App\Category');
}
}


--

class Category extends Model
{
protected $fillable = ['name','slug'];
protected $dates = ['created_at'];

public function articles()
{
return $this->hasMany('App\Article');
}
}

Answer

You miss the category_id.
Change

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

To

protected $fillable = ['title','body','published_at','user_id', 'category_id'];