On your User model can you post the code of the rawSettings method
Eager loading of a model relation works in browser, but not in PHPunit test
I have a really weird issue that I am not able to solve right now. The full code is available on Github.
Status Quo
Currently, I have the standard user model and a settings model. A setting is bound to a user via a user_id field. The user model has a $user->rawSettings relation which eager-loads the related settings. I use eager loading here to prevent database calls for each single setting checked in the application. All settings are transformed into a $key => $value collection and available via a $user->settings() method.
There is a helper function usersettings($key) which returns a setting for the current user like so: auth()->user()->setting($key).
This is working without issues in the application while running in the browser.
The issue
However, I implemented tests for some features and the helper function stopped working (corresponding test). I thought that I may have missed something so I double checked the process:
-
auth()->user()returns the current user with the ID 1 -
Setting::first()returns a valid setting entry connected to the user via user_id = 1 -
auth()->user()->rawSettingsis empty, despite the fact that there are entries in the database?! -
auth()->user()->rawSettings()->get()correctly returns all entries. WTF?! -
usersettings('...')therefore returns null for every key.
Why is that eager loaded relation for user settings working in the browser, but not in the PHPunit test? Why are eager-loaded relations empty while the non-eager-loaded relations correctly return all entries?
Tried solutions
I already tried adding the load('rawSettings') method to the helper function (auth()->user()->load('rawSettings')->...), which then returns the correct results. But this leads to numerous queries being executed for each single call uf the usersettings() method. This is not a proper solution for me.
I tried adding the $with = ['rawSettings'] property to the user model as suggested here. Nothing changes, the relations are still not loaded in the unit tests.
Please or to participate in this conversation.