Caching data in sections

Submitted by gerob - 11 years ago

This is specific to using Redis for caching. You can group your keys in sections to allow for easily clearing the cache on just a section of data. Couple notes: 1. You have to have 'cluster' set to false in app/config/database.php under the 'redis' key. 2. Remember to pass through variables into the closure with 'use'. 3. Have fun!

// cache the index of users
$per_page   = Input::get('per_page', 10);
$page       = Input::get('page', 1);
$key = "user_".$per_page.$page;
$object = Cache::section('all-users')->rememberForever($key, function() use ($per_page) {
    // return the results from database query
    $users = Users::all();
    return $users->paginate($per_page)->toArray();
});

// then when you create, update or delete a user
Cache::section('all-users')->flush();

// Caching individual users
$object = Cache::section('user')->rememberForever($id, function () use ($id) {
    return User::find($id)->toArray();    
});

// then when you create, update or delete a user
Cache::section('user')->forget($id);