Those are the following migration files:
User migration
Schema::create('users', function (Blueprint $table) {
$table->uuid('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
Log migration
Schema::create('log', function (Blueprint $table) {
$table->uuid('id');
$table->boolean('statu');
$table->timestamps();
$table->foreign('id')->references('id')->on('users')->onDelete('cascade');
});
When I run the migrations it shows:
PDOException::("SQLSTATE[HY000]: General error: 1005 Can’t create table
laravel
.log
(errno: 150 "Foreign key constraint is incorrectly formed")")
I also tried:
Schema::create('log', function (Blueprint $table) {
$table->uuid('id');
$table->boolean('statu');
$table->timestamps();
});
Schema::table('log', function($table) {
$table->foreign('id')
->references('id')
->on('users')
->onDelete('cascade');
});
Schema::create('log', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('foreign_id');
$table->boolean('statu');
$table->timestamps();
});
Schema::table('log', function($table) {
$table->foreign('foreign_id')
->references('id')
->on('users')
->onDelete('cascade');
});
But still not working.
— I have solved this problem
User
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
log
Schema::create('log', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('user_id');
$table->boolean('statu');
$table->timestamps();
});
Schema::table('log', function($table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
2
Answers
Please use $table->id(); instead of $table->uuid(‘id’);
Try adding to your users table :
Nothing here indicate to you database that id is the primary key.
Then you should call your foreign key as "name_of_the_table"_id.
For you it should be :
And finally you can add :
The complete code is something like that :