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

Hadayat's avatar

Build relation of two table and apply onDelete('cascade). It's not working

Hello Guys,

I am building the relation b/w two tables and apply the onDelete method but it' not work for me.

Error:

SQLSTATE[HY000]: General error: 1005 Can't create table laravel_cms.posts (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table posts add cons traint posts_user_id_foreign foreign key (user_id) references users (id) on delete cascade).

Please read these line before answering.

  1. My primary key and foreign key has same data type and same size.
  2. I have index box columns.
  3. I assign nullable method to foiegn key but it does't work.
  4. I also assign unsigned method to foreign key but it does't work.
  5. My column has same schema object.
0 likes
5 replies
Tray2's avatar

Show us your migration files.

Hadayat's avatar
 public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->index();
            $table->integer('category_id')->unsigned()->index();
            $table->integer('photo_id')->unsigned()->index();
            $table->string('title');
            $table->string('body');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }
Tray2's avatar
Tray2
Best Answer
Level 73

table->id() is a bigInteger so all your foreign keys needs to be the same format.

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});
Hadayat's avatar

It's works for me. Thanks dear you made my day.

Snapey's avatar

Mark Tray2's answer correct, not your own

Please or to participate in this conversation.