SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Created at 22-Jul-2021 , By samar

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

We will use programming in this lesson to attempt to solve the "SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint".

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint is the most common error which occurs when you try to create a table structure using the migration command in Laravel
  • Things to keep in mind while migrating the migration file with foreign key to avoid errors in Laravel

    Migration files order issue -  
      //Migration files with foreign keys should be at the bottom in the migration folder or after the parent table (related table). Like if you have discount_id (foreign key) in the products table then the discounts table should be at the top or before the products table. You can also change the file name (digits in migration file) to solve the order issue.
    Create parent table first - 
      //Create the parent table (related table). Like you have created the products table with a foreign key (discount_id) but you did not have created the discounts (parent) table then It will also give errors while migration.
    
  • Add foreign id category_id in posts table using migration in laravel 8

    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->foreignId('category_id')->constrained();
        $table->timestamps();
    });
    

    You can create a foreign key category_id in the posts table. Before creating the table structure for the posts table you have to create table structure of the categories table in Laravel. You have to create a migration file for the categories table and the migration file should be before the posts table migration file in the database/migrations directory.

  • Pass table name to the constrained method in laravel

    Schema::table('posts', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained('users');
    });
    

    If your table name does not match Laravel's conventions while passing the column name to pivot table or the column with foreign key in laravel. Then you can pass table name to constrained method to avoid SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint error in laravel while execting the migration command.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.