Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mozew's avatar
Level 6

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `borujerd_amintamir`.`blogs` (errno: 121 "Duplicate key on write or u pdate")")

How to solve it?

error

public function up()
{
    Schema::create('blogs', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->nullable()->constrained()->cascadeOnDelete();
        $table->string('title');
        $table->string('slug');
        $table->string('link');
        $table->string('image')->nullable();
        $table->text('body');
        $table->string('keywords');
        $table->string('meta_description');
        $table->timestamps();
    });
}
0 likes
13 replies
Lara_Love's avatar

@mozew Can't create table `borujerd_amintami you show Schema::create('blogs', function (Blueprint $table) {

Lara_Love's avatar

@mozew maybe you should first borujerd_amintami table then blogs or upside down

mozew's avatar
Level 6

@LoverCode The problem is fromuser_id.

SQLSTATE[HY000]: General error: 1005 Can't create table borujerd_amintamir.blogs (errno: 121 "Duplicate key on write or update") (SQL: alter table blogs add constraint blogs_user_id_foreign foreign key (user_id) references users (id) on delete cascade)

Sinnbeck's avatar

@mozew Can you run php artisan migrate --pretend and post the output?

Shivamyadav's avatar

Try using this table migration code add these two lines in your migration table file remove this code

 $table->foreignId('user_id')->nullable()->constrained()->cascadeOnDelete();

and add this and try to migrate it then

$table->foreignId('user_id')->unsigned()->index()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Or take this down code and replace it from your migration file code

public function up()
{
    Schema::create('blogs', function (Blueprint $table) {
        $table->id();
		$table->foreignId('user_id')->unsigned()->index()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('title');
        $table->string('slug');
        $table->string('link');
        $table->string('image')->nullable();
        $table->text('body');
        $table->string('keywords');
        $table->string('meta_description');
        $table->timestamps();
    });
}

xeno's avatar

did you try specifying what table does the foreign key being referenced to ?

$table->foreignId('user_id')->nullable()->constrained('relatedTable')->cascadeOnDelete();

Please or to participate in this conversation.