This question has already been asked many times, I went through all the answers, but none solves the error I'm getting.
I'm using Laravel 5.2
I have 2 tables - Classifieds and Categories. When I want to create a classified, I get the error message:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
myclassified
.classifieds
, CONSTRAINTclassifieds_category_id_foreign
FOREIGN KEY (category_id
) REFERENCEScategories
(id
))
Migration files defined like this:
for classifieds
table:
public function up()
{
Schema::create('classifieds', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('classifieds');
}
for categories
table:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
and to add the foreign key,
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
The Models are:
Classified
model:
class Classified extends Model
{
protected $table = 'classifieds';
protected $fillable = ['title', 'category_id', 'description', 'price'];
protected $hidden = [];
public function category(){
return $this->belongsTo('App\Category');
}
}
and the Category
model:
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
protected $hidden = [];
public function classifieds(){
return $this->hasMany('App\Classified');
}
}
and the store method in controller is defined like this:
public function store(Request $request)
{
$title = $request->input('title');
$category_id = $request->input('category_id');
$description = $request->input('description');
$price = $request->input('price');
Classified::create([
'title' => $this->title,
'category_id' => $this->category_id,
'description' => $this->description,
'price' => $this->price
]);
return \Redirect::route('classifieds.index')
->with('message', 'Ad created');
}
What is my mistake in database set up?