I want to create two table users
and roles
. My codes are below:
2014_10_12_000000_create_users_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('role')->unsigned();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role')
->references('id')
->on('roles');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
2016_03_09_004256_create_roles_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('roles');
}
}
When I run php artisan migrate
the following error appear.
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table
trucking
.#sql-1240_44
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableusers
add constraint u sers_role_foreign foreign key (role
) referencesroles
(id
))[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table
trucking
.#sql-1240_44
(errno: 150 "Foreign key constraint is incorrectly formed")