Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel user specific caching

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?

like image 987
Hardist Avatar asked Dec 30 '17 19:12

Hardist


People also ask

Does Laravel have caching?

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.

How do I enable caching in Laravel?

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.

Where does Laravel store cached data?

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.

What is Memcached in Laravel?

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.


1 Answers

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());
like image 155
Alexey Mezenin Avatar answered Sep 20 '22 14:09

Alexey Mezenin