Skip to main content

Admin Role and Companies

Premium
6 min read

Comments & Discussion

A
Ahmad ✓ Link copied!

Hello, The test failed at my end, I had to remove the constrain at the add_role_id_to_users_table, then everything went as expected.

KD
Kwesi Danquah ✓ Link copied!

the tests failed at my end too so i just removed the constrained from the role_id

N
Nerijus ✓ Link copied!

Just reran this test and it's all green for me. Maybe you are missing something. Without some code and error message can't help.

A
Ahmad ✓ Link copied!

This is the error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (testing_reservation_project.users, CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id)) (Connection: mysql, SQL: insert into users (name, email, email_verified_at, password, remember_token, role_id, updated_at, created_at) values (Emely Greenfelder IV, konopelski.edwin@example.com, 2023-07-08 20:59:46, $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi, 56Sx9OSLgp, 3, 2023-07-08 20:59:46, 2023-07-08 20:59:46))

N
Nerijus ✓ Link copied!

My guess is you don't have roles seeded. Constraints should be always used.

J
jocagutierrezz ✓ Link copied!

The problem is that every Test is using use RefreshDatabase; to refresh tables after testing, in my case by default it´s not seeding at all, just migrating, so I just add public $seed = true; in every single test to let know that I want to seed tables as well, this works for me and didn´t have to remove constrained from migration.

Solved it in last comment on: https://laracasts.com/discuss/channels/testing/manually-seed-refreshdatabase

N
Nerijus ✓ Link copied!

You don't need to add it in every test. Add in the TestCase.php and it will work for every test.

Y
yussuf ✓ Link copied!

This worked for me

J
jwinder ✓ Link copied!

@jocagutierrezz youre the goat man thanks

L
Lister ✓ Link copied!

@Ahmad add role_id to your DatabaseSeeder just like this.

$this->call(RoleSeeder::class);

User::factory()->create([ 'role_id' => 1, ]);

YN
Yuri Neves ✓ Link copied!

Need to create a database to run the tests in laravel?

PK
Povilas Korop ✓ Link copied!

Yes it should be either a separate MySQL database, or SQLite database in memory. Watch this lesson from my course about testing for beginners.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.