I've never done much with caching, but am trying to play around with it a bit now. I have a dashboard that returns a lot of data, and to make the load a bit lighter, I am caching data like so:
return cache()->rememberForever('something', function () {
return auth()->user()->something()->get();
});
Where "something" is just a related model. When creating a new record, in the controller store
and update
methods I just do this:
cache()->forget('something');
This all works flawlessly. But when I login with another user, all cached data from the previous user is obviously being displayed on the dashboard.
Is there an easy way to simply cache data per user?
Caching per user does not necessarily make much sense that I can think of off the top of my head (not to say there isn't the odd use-case out there for this). The purpose of caching is not to be a "session"-store for a given user, but lighten the load across the entire application for all users.
I would start by asking why you need to cache per user. Perhaps there is a fundamental misunderstanding as to how Laravel Caching works, or perhaps the application architecture is poorly designed? My recommendation is to cache everything but user-related information.
There are several packages out there that can help with this, I have created one to scratch my own itch: https://github.com/GeneaLabs/laravel-model-caching. This package aims to abstract caching out and automatically cache database interactions (except the user information) for you. This takes all the WHERE clause conditions into account, so each query would be cached differently for different WHERE clauses. This means that your user-sensitive data will be returned only for the correct user (as presumably the user ID or some other identifier would be in the WHERE clause).
You could do something like this to store user object for each user separately:
To get the data for an authenticated user: