Laravel Caching User Related Caching

- 1 answer

Lets say i have a system where i have 3 models manufacturer, vehicles and Brand.

Vehicles -> One to one -> brand / manufacturer
Manufacturer -> One to many -> brand / vehicles
Brand -> One to many -> Vehicles
Brand -> One to One  -> Manufacturer

The system has an admin panel and a user panel.

Admin Panel:

In the admin panel i usually do something like this

Vehicle::with('manufacturer', 'brand')->get();

I also dont cache this query, and i think its fine as i dont need much speed in the admin area.

User Area:

But in the user area, i use much simpler queries as i have read that simpler queries are better as they can be cached. So i use one query to get manufacturer of a vehicle and another query to get brand of the vehicle. Then i just prepare an array to send to the view. Here is a sample query

Manufacturer::where('vehicle_id', $vehicleID)->where('is_active', 1)->get($columns);

every users will have different vehicles. Lets say user A has 10 vehicles and user B has 20 vehicles.

So my question is how can i cache user specific queries, that are changing constantly?

Secondly is there any any reliable but automated way of doing this instead of changing the code, something like memcache or similar?

I have also heard about redis caching, i think it grabs all the data from mysql and then stores in redis and next time it just fetches it from redis instead of mysql. Is this better? and can i do this without changing much code?

NOTE: One more thing to keep in mind is that this system has to be auto scalable, i.e used on aws beanstalk or something similar so the databases should be synced. Dont know yet how the synching works.

As always, any help is appreciated.



code example.

$result = {your result} 

if (!Cache::has('user' . $userID) || env('CACHE_TIME') < 0) {
    Cache::put('user' . $userID, $result, env('CACHE_TIME'));
} else {
    $result = Cache::get('user' . $userID);

.env file

CACHE_TIME = 240 // cache time minutes, you can disable cache with -1

after user buy a vehicle

Cache::forget('user' . $userID);

Note: you can change cache method. More info at