I'm new to Laravel and databases in general. I'm writing a web application for student evaluations. I have an existing MySQL database that contains everything I need already; however, I am using Laravel's auth user table and trying to add a foreign key that references a Teacher table in the MySQL database. I keep getting the following error...
php artisan migrate:fresh
In Connection.php line 664:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter tableusers
add constraintusers_teacher_id_foreign
foreign key (teacher_id
) referencesp4j
.teacher
(teacher_id
))In Connection.php line 458: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
My code is as follows...
config/database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DP_PORT', '3306'),
'database' => env('DB_DATABASE', 'p4j'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DP_PASSWORD', '**mypassword**'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
database/migrations/2014_10_12_000000_create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('teacher_id')->unsigned();
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->foreign('teacher_id')->references('teacher_id')->on('p4j.teacher');
});
}
app/User.php
protected $fillable = [
'name', 'email', 'password', 'teacher_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];