Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error creating table with foreign key Laravel

This is my first table migration file :

public function up()
{
    Schema::create('produits', function (Blueprint $table) {
        $table->id();
        $table->string('nom',255)->unique();
        $table->string('photo')->default('default.png');
        $table->longText('description');
        $table->float('prix');
        $table->unsignedBigInteger('categorie_id');
       
        $table->foreign('categorie_id')->refrences('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });
}

This is my second table migration file :

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('nom',255)->unique();
        $table->timestamps();
    });
}

This is the error i’m getting :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'produits' already exists (SQL: create table `produits` (`id` bigint unsigned not null auto_increment primary key, `nom` varchar(255) not null, `photo` varchar(255) not null default 'default.png', `description` longtext not null, `prix` double(8, 2) not null, `categorie_id` bigint unsigned not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

I tried both : php artisan migrate , php artisan migrate:refresh

>Solution :

You can try to remove the tables from database and before you run the migrations again, make sure categories migration is created first.
If you have created produits migration first, it won’t work because when migrations are run, the produits table is created first and it will not find the referenced table which does not exist yet. Therefore, the foreign key constraint will not be created.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading