Closed douglasviehbeck closed 3 years ago
This won't work unfortunately and isn't really a bug... the underlying encoder uses the class of object it is given to determine how to encode it to a JSON API resource. So you cannot use the same class for multiple different resource types.
There's no way to fix this, i.e. it isn't a bug... because in the scenario you've shown, how would the encoder know which resource type to use (users
, login
, etc) when it encounters a User
class object?
We however do something similiar to what you are trying... we have a users
and user-accounts
resource types, that both effectively map to a User
model. What we do however is have a UserAccount
class that takes a User
model in its constructor - i.e. we wrap the user model in a presenter class, so the encoder knows what to do.
Then our mapping is:
'resources' => [
'users' => \App\Models\User::class,
'user-accounts' => \App\JsonApi\UserAccount::class,
]
@lindyhopchris How does the part with the User as construct parameter work?
Can you provide an example?
@thoresuenert we have to use custom adapters for the user-accounts
resource, so that it can create the UserAccount
classes correctly. I'd like to document this better in the next version, as I've got some ideas of how to simplify it, but in the meantime custom adapters are documented here:
https://laravel-json-api.readthedocs.io/en/latest/basics/adapters/#custom-adapters
Closing due to lack of activity.
Hi, I might have found an issue in the resource resolution. I have some "fake" resources that could not be met by any model in the project and as they were related to the User model i thought it would be handy to map the resources to it: But now, when i send a request to
/users
the resulting type ispassword-reset
. After some time digging the code i found out that the resource classes (Adapter/Schema/Validators) are resolved through the model instance not the resource name and so i'm not able to have more than one resource mapped to the same model. Is this an expected behavior?