Level 70
@lyndon Can you try this?
$table->ulid('id')->primary();
$table->string('name');
$table->foreignId('parent_id')->nullable()->constrained('folders')->onDelete('cascade');
$table->timestamps();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have the following migration code:
$table->ulid('id')->primary();
$table->string('name');
$table->foreignUlid('parent_id')->nullable()->constrained(table: 'folders')->onDelete('cascade');
$table->timestamps();
the id field is clearly indexed as the primary key. But I'm getting the following error when I run the migration:
SQLSTATE[HY000]: General error: 1822 Failed to add the foreign key constraint. Missing index for constraint 'folders_parent_id_foreign' in the referenced table 'folders' (SQL: alter table `folders` add constraint `folders_parent_id_foreign` foreign key (`parent_id`) references `folders` (`id`) on delete cascade)
I found the issue, the foreign key cannot be added without creating the table first. I had to add the foreign key in a separate Schema.
public function up()
{
Schema::create('folders', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->foreignUlid('tenant_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
Schema::table('folders', function (Blueprint $table): void {
$table->foreignUlid('parent_id')->nullable()->constrained('folders')->onDelete('cascade');
});
}
Please or to participate in this conversation.