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?
Laravel supports popular caching backends like Memcached, Redis, DynamoDB, and relational databases out of the box. In addition, a file based cache driver is available, while array and "null" cache drivers provide convenient cache backends for your automated tests.
To enable Laravel caching services, first use the Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository, as they provide access to the Laravel caching services. The Factory contract gives access to all the cache drivers of your application.
Laravel provides a unified API for various caching systems. The cache configuration is located at app/config/cache. php . In this file you may specify which cache driver you would like used by default throughout your application.
Adding caching to Laravel. Memcache is an in-memory, distributed cache. Its primary API consists of two operations: SET(key, value) and GET(key) . Memcache is like a hashmap (or dictionary) that is spread across multiple servers, where operations are still performed in constant time.
You could do something like this to store user object for each user separately:
return cache()->rememberForever('something' . auth()->id(), function () {
return auth()->user()->something()->get();
});
To get the data for an authenticated user:
cache('something' . auth()->id());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With