Laratrust polymorphic user models returns wrong roles

345 views Asked by At

I am using Laratrust to add roles to my User model. I want to add another table to use roles as well. I added modelAs to the config but Laratrust is confusing the two types. I get the roles from user with id[3] when querying modelA with id[3]. All I changed in the config was the user_models array like so:

'user_models' => [
    'users' => 'App\User',
    'modelAs' => 'App\ModelA'
],

I then added the modelA in role_users and set user_type to App\ModelA

|user_id    |role_id    |user_type        |
|-----------|-----------|-----------------|
|3          |6          |App\User         |
|3          |7          |App\User         |
|3          |8          |App\ModelA       |

Is the polymorphic relationship not supposed to know that I am not using the User model when I use the statement $modelA->roles?

I believe the problem has to do with caching the roles, because the key used to cache the roles in redis is laratrust_roles_for_user_3 which would the same for both variations of user_type. So the Cached values are overwritten? How am I supposed to work around that?

Any help would be appreciated.

1

There are 1 answers

0
Daniel On

I took a deeper look at how the package stores values in the cache. In the LaratrustUserDefaultChecker the cache key is built up using $cacheKey = 'laratrust_roles_for_'.$this->userModelCacheKey() .'_'. $this->user->getKey(); and the userModelCacheKey() function is as follows:

public function userModelCacheKey()
{
    if (!Config::get('laratrust.use_morph_map')) {
        return 'user';    // <-- this caused the confusion.
    }

    foreach (Config::get('laratrust.user_models') as $key => $model) {
        if ($this->user instanceof $model) {
            return $key;
        }
    }
}

At the moment I am not using the morph_map setting, thus the key will be the same for models with the same ID. This is the cause of the confusion. A quick test showed that if I set 'use_morph_map' => true in the laratrust config and change the user_type column to match the key of user_models then there are two cache entries corresponding to my two models. And now ->hasRole returns the correct result!

Note: I had to clear my cache before the test because it would show the wrong stored values.