errno: 150 “Foreign key constraint is incorrectly formed”) (Connection: mysql, SQL: alter table `users` add constraint `users_role_id_foreign`

Published on Sep 29, 2024 by

Illuminate\Database\QueryException

SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name ‘role_id’ (Connection: mysql, SQL: create table `users` (`id` bigint unsigned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `password` varchar(255) not null, `role_id` bigint unsigned not null, `role_id` bigint unsigned not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` timestamp null, `deleted_at` timestamp null) default character set utf8mb4 collate ‘utf8mb4_unicode_ci’)

at vendor\laravel\framework\src\Illuminate\Database\Connection.php:829
825▕ $this->getName(), $query, $this->prepareBindings($bindings), $e
826▕ );
827▕ }
828▕
➜ 829▕ throw new QueryException(
830▕ $this->getName(), $query, $this->prepareBindings($bindings), $e
831▕ );
832▕ }
833▕ }

1 vendor\laravel\framework\src\Illuminate\Database\Connection.php:587
PDOException::(“SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name ‘role_id'”)

2 vendor\laravel\framework\src\Illuminate\Database\Connection.php:587
PDOStatement::execute()

 

Migrations:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create(‘users’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(’email’)->unique();
$table->string(‘password’);
$table->foreignId(‘role_id’)->constrained()->onDelete(‘cascade’);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();

$table->charset = ‘utf8mb4’;
$table->collation = ‘utf8mb4_unicode_ci’;
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists(‘users’);
}
};

 

Solution/Fixed/ Solved:

change foreignId to unsignedInteger

 

This solve my problem.

About the Author: Gossip

Leave a Reply

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

PHP Code Snippets Powered By : XYZScripts.com