VinayKesharwani's avatar

Feature Example Test fails when using queries in Service Provider

Steps to reproduce:

  • Create a new Laravel App
  • Add any eloquent query in AppServiceProvider say User::first()

Upon running Feature/ExampleTest.php, it fails. You can also use RefreshDatabase trait but it keeps failing.

Why add an eloquent query in AppServiceProvider?

  • There can be various cases. Say you are running Multi-tenant application and check the tenant account, or you wish to set config dynamically from the database etc.

Can anyone help with this?

0 likes
3 replies
PovilasKorop's avatar

From what I remember, it failed for me as well because at the time of AppServiceProvider is loaded, the database migrations may not have happened.

So I would add if Schema::hasTable('users') in the AppServiceProvider before calling the model.

VinayKesharwani's avatar

@PovilasKorop I was wrong. I have updated my question. The test fails for all database drivers.

Using conditions won't actually test the code. So it is not the solution.

Does it mean that ServiceProviders are not the correct place to write queries if you can't test them?

PovilasKorop's avatar

@VinayKesharwani Yes, in most cases Service Provider is a configuration mechanism to register some classes, not for the action of those classes itself.

1 like

Please or to participate in this conversation.