I want to create 2 tables:
- A table called
roles - And a table called
users
In users I want to have a column called role_id and it should be a reference to roles table.
This is how roles table should look like:
So here is a migration for user table:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigInteger('role_id')->unsigned();
$table->foreign('role_id')->references('role_id')->on('roles');
$table->timestamps();
});
And here is a migration for roles talbe:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
});
The error I get when I run php artisan migrate
SQLSTATE[HY000]: General error: 1005 Can't create table
my_db.users(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableusersadd constraintusers_role_id_foreignforeign key (role_id) referencesroles(role_id))

Change references('role_id') in references('id') which means that references in column 'id' in roles table:
Also you should create first roles table and after that users table. Just change the dates on database/migrations like this (example):
run:
This way first will be created the roles table and then users table which will handle a foreign key which references 'id' column in roles table.