I have two tables. Courses and the default laravel users table. I am including the course_id as a foreign key in the users table, but I am getting an error when trying to migrate since the courses table is migrated after the users table is migrated.
Error: SQLSTATE[HY000]: General error: 1005 Can't create table
scholar_net
.users
(errno: 150 "Foreign key constraint is incorrectly formed") (Connection: mysql, SQL: alter tableusers
add constraintusers_course_id_foreign
foreign key (course_id
) referencescourses
(id
) on delete cascade)
Users table code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('is_admin')->default(false);
$table->string('user_type')->nullable();
$table->string('dob')->nullable();
$table->string('address')->nullable();
$table->string('telephone_no')->nullable();
$table->unsignedBigInteger('course_id');
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->boolean('account_status')->default(true);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Course table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->timestamps();
//$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('course_title');
$table->string('course_description');
$table->integer('course_price');
$table->boolean('course_status')->default(true);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('courses');
}
};