laracoft's avatar

Enumerate relations of a model

I think it makes sense for every model each to have a test that has a list of "authorized" relations, and it enumerates through the model and ensure that nothing has been added/removed.

Is there an easy way to enumerate this list from the model using PHPUnit/Laravel?

0 likes
6 replies
tykus's avatar

Not possible currently unless you implement a method to interrogate the model class using the Reflection; you may also need to properly hint the return types as the appropriate Relation class.

Check out the model:show command implementation for some guidance - located in the getRelations method of vendor/laravel/framework/src/Illuminate/Database/Console/ShowModelCommand.php

laracoft's avatar

@tykus

Yea thanks, I suppose I have to get my hands dirty with reflecting. So type hint is also good because if it was not added, the test will fail.

tykus's avatar

@laracoft the ShowModelCommand actually does not use the return type; instead checking for the use of str_contains($code, '$this->'.$relationMethod.'(') where they loop over an array of belongsTo, hasMany method names. However, I expect this will falter whenever you use the One of Many approach where you convert an existing HasMany relation. In that case, the return type approach (backed by a PHP CS Fixer rule to enforce return types on methods) is preferred IMHO.

martinbean's avatar

@laracoft What do you mean by “authorised” relations? And ensures nothing has been added/removed for what purpose? What is the actual problem you‘re trying to solve here?

Please or to participate in this conversation.