Laravel Eloquent – Integrity constraint violation: 1452 foreign key constraint or General error: 1005

Are¬†you trying to set-up a foreign key constraint on one of your tables and you’re getting a 1452 error?

[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

 

You might also get a General error: 1005

[PDOException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `app`.`#sql-33d4_1a2` (errno: 150 "Foreign key constraint is incorrectly formed")

 

This is a MySql issue and not a Laravel one.

There could be a number of issues causing this but the most likely is that the reference table has no data in it. For example:

$table->foreign('brand_id')->references('id')->on('brands');

 

You need to make sure the ‘brands’ table has some data in it before you can create the foreign key.

If you have created a seeder for this table (and I recommend you do) then you can call the seeder after you have created the table. In your migration file add the Artisan facade:

use Illuminate\Support\Facades\Artisan;

 

And then call the seeder after you have created the table:

    public function up()
    {
        Schema::create('fabrics', function (Blueprint $table) {
            // create the table
        });
        
        Artisan::call('db:seed'));
    }

 

If you wish to call only one seeder which is what I recommend in this case then you can pass the seeder as an array like so:

Artisan::call('db:seed', array('--class' => 'FabricsTableSeeder'));

 

This will prevent the above error codes when you migrate on a new system or reset your migrations, it will ensure the tables have the data they need to create the foreign key constraints.

Leave a Reply

Your email address will not be published. Required fields are marked *