"Foreign key constraint is incorrectly formed" on Laravel

  laravel, laravel-7, laravel-8, php

I’m trying to create a new table for my database.

I previously created a table (tipo) with a PK (IdCorso), then another table(corsoscii) with a foreign key associated with tipo.

When I execute the artisan command for corsoscii
php artisan migrate --path='./database/migrations/2021_02_23_155544_create_corsoscii_table.php' it gives me this error:

("SQLSTATE[HY000]: General error: 1005 Can't create table impianto_scii.corsoscii (errno: 150 "Foreign key constraint is incorrectly formed")")

This is the setup code for "tipo"

public function up()
    {
        Schema::create('tipo', function (Blueprint $table) {
            $table->increments('idCorso');
            $table->string('descrizione');
            $table->timestamps();
        });
    }

…and for "corsoscii"

  public function up()
{
    Schema::create('corsoscii', function (Blueprint $table) {
        $table->increments('idCorso');
        $table->integer('tipo');
        $table->string('nome');
        $table->integer('membriMax');
        $table->date('inizio');
        $table->date('fine');
        $table->timestamps();

    });

    Schema::table('corsoscii', function(Blueprint $table){

        $table->foreign('tipo')
            ->references('idCorso')->on('tipo')
            ->onDelete('cascade');
        
        $table->primary('idCorso');
    });
}

I’m a neophyte with Laravel, any advice is welcome.

Source: Laravel

Leave a Reply