I'm having this error in my laravel application.
these are the tables:
Post
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
$table->integer('user_id')->unsigned();
});
Categories
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Post_Category
Schema::create('post_category', function (Blueprint $table) {
$table->integer('post_id')->unsigned()->unique()->nullable();
$table->integer('cat_id')->unsigned()->unique()->nullable();
$table->timestamps();
});
Foreign Keys
Schema::table('posts', function (Blueprint $table) {
$table->foreign('id')->references('post_id')->on('post_category')->onDelete('cascade');
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('id')->references('cat_id')->on('post_category')->onDelete('cascade');
});
Here my models
class Categorie extends Model
{
protected $table = 'categories';
public function posts() {
return $this->hasMany('App\PostCategory');
}
}
...
class Post extends Model
{
public function author() {
return $this->belongsTo('App\User', 'user_id');
}
public function featuredImage() {
return $this->belongsTo('App\Media', 'media_id');
}
public function categories() {
return $this->hasMany('App\PostCategory');
}
}
...
class PostCategory extends Model
{
protected $table = 'post_category';
}
Here the controllers
Store Category:
public function store(StoreCategory $request)
{
$category = new Categorie;
$category->name = $request->input('name');
$category->save();
return redirect('/admin/categories')->with('status', 'New category created!');
}
Store post
public function store(StorePost $request)
{
$post = new Post;
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->media_id = $request->input('media_id');
$post->user_id = $request->input('user_id');
$post->save();
return redirect('/admin/posts')->with('status', 'New post created!');
}
Having this error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
the_film_corner.tfc_categories, CONSTRAINTcategories_id_foreignFOREIGN KEY (id) REFERENCEStfc_post_category(cat_id) ON DELETE CASCADE) (SQL: insert intotfc_categories(name,updated_at,created_at) values (News, 2017-02-26 14:51:15, 2017-02-26 14:51:15))
Thanks