Caching Groups within Rainlab Users

Hi,

I just do some caching work within my website and also had a look at the groups from Rainlab / Users.
Depending on the Users Groups, some things in the frontend are shown differently.
In order to achieve this, I wrote a custom component adding parameters to the page via $this->page->something depending on the group of the user.

I recognized the group query $user->groups is called on every page load, so I wanted to cache this.

Here’s what I did to cache the users groups in my component:

        $usersGroups = Cache::rememberForever(
            "user_" . $user->id,
            function () use ($user) {
                return $user->groups->pluck('code')->toArray();
            }
        );

…and here my changes to the UserModel (I extend the Rainlab User Plugin):

 UserModel::extend(function ($model) {
			# [.....]
            $model->bindEvent('model.afterSave', function () use ($model) {
                Cache::forget('user_' . $model->id);
            });
        });

So basically I cache the users groups, store them as array in a cache item called “user_id” and whenever the user is updated, I remove the cache item in the afterSave method.

It works, but honestly, this doesnt feel like the best possible solution.

I wonder if there’s some better possibility to realize this. Any input is welcome…

Hey @LordRazen

This is the way Laravel recommends. Initially, they had a ->remember() method chained to the query that cached the base lookup query internally, but they dropped it because serializing and unserializing the model was too difficult. They replaced it with an approach similar to what you’ve done here, caching a simple object at the point where it is needed.

Using the event to clear the cache work very well too! :+1:

1 Like