Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

a.verrecchia's avatar

php artisan test: Integrity constraint violation: 19 FOREIGN KEY constraint failed

Why is it that when I execute an insert request through Postman to add a user record, it gets inserted correctly, but when I run the test as shown below, I get the following error?

SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed (SQL: insert into "users" ("firstname", "lastname", "email", "password", "role_id", "status", "updated_at", "created_at") values (John, Doe, [email protected], $2y$04$VBS2Tmf2dFEu7mhC36rkxeedhihJQudNrPl/0I/33Z84DmrUYYsuu, 1, active, 2023-04-05 08:45:07, 2023-04-05 08:45:07))

public function testRegistrationSucceedsWithUserRole()
{
    $response = $this->postJson('/api/auth/register', [
        'firstname' => 'John',
        'lastname' => 'Doe',
        'email' => '[email protected]',
        'password' => 'password',
        'password_confirmation' => 'password',
        'role_id' => 1
    ]);

    $response->assertStatus(200)->assertJsonStructure([
        'access_token',
    ]);
}
0 likes
4 replies
Snapey's avatar

without knowing your db fk constraints I would say you don't have a role with id=1 in the blank test database

a.verrecchia's avatar

@Snapey I tried a Role::all() for testing purposes (as I did for the other models) but it returns empty with no items. The database is populated, so I don't understand why.

Snapey's avatar

@a.verrecchia your test setup should be an empty database, so you need to create role 1 first

1 like

Please or to participate in this conversation.