If you are using Laravel 9, just do this:
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
and remove this:
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm trying to migrate my DB and I get this error.
SQLSTATE[HY000]: General error: 1005 Can't create table
waddle.posts(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tablepostsadd constraintposts_user_id_foreignforeign key (user_id) referencesusers(id) on delete cascade)1 D:\tej\laravel\waddle\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table
waddle.posts(errno: 150 "Foreign key constraint is incorrectly formed")")
2 D:\tej\laravel\waddle\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501 PDOStatement::execute()
I already tried foreign-key-constraint-is-incorrectly-formed-laravel and laravel-migration-errno-150-foreign-key-constraint-is-incorrectly-formed and I added unsigned to my Schema and it didnt work and I even tried adding users table above posts table(It worked and now I'm getting this error) .Here's my code for posts
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->text('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->string('image')->nullable();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
I'm using Laravel 9 edit sorry for late reply but I just created a new project and did the same and it worked perfectly maybe I might have made some error nd didnt know about it.Nevertheless I thank you all for helping begginers like me.
Please or to participate in this conversation.