Search code examples
laravellaravel-migrations

Integrity constraint violation when using a Foreign key for a user role


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, >CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES >roles (id))

If you know where is my problem let me know !


Solution

  • Since your structure depends on the fact that every use must have a role, you should include the insertion of the default role in your migration.

    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();
            });
    
            DB::table('roles')->insert([
                'id' => 1, //must be 1
                'name' => 'default',
                'description' => 'default role (just registered)',
                'created_at' => \Carbon\Carbon::now(),
                'updated_at' => \Carbon\Carbon::now(),
            ]);
        }
    
    [...]
    
    }