I'm trying to define a role for my users using a "role_id" foreign key which referes to the "id" of my "roles" table.
The migrations worked well but when I'm trying to register I get an error.
Migration users
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->char('nni', 6);
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->unsignedBigInteger('role_id')->default(1);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles');
});
}
Models/User
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nni', 'firstname', 'lastname', 'email', 'role_id', 'admin', 'password',
];
[...]
public function role()
{
return $this->belongsTo(Role::class);
}
}
Migration roles
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
[...]
}
The error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update >a child row: a foreign key constraint fails (
projectsms
.users
, >CONSTRAINTusers_role_id_foreign
FOREIGN KEY (role_id
) REFERENCES >roles
(id
))
If you know where is my problem let me know !
users
table is being created before theroles
table, it will fail the constraint when it tries to create. foreign tables should be created first before trying to reference them. – Erichrole_id
doesnt reference an entry in yourroles
table. Is there a role id = 1 in yourroles
table ?$table->unsignedBigInteger('role_id')->default(1);
– N69SSQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
users` add constraintusers_role_id_foreign
foreign key (role_id
) referencesroles
(id
))` – Petouxrole_id
in the tableusers
to 1. If you have users without roles, set the field as nullable$table->unsignedBigInteger('role_id')->nullable();
– N69S