Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Selective Caching

I'm developing one of my first applications with the Laravel 4 framework (which, by the way, is a joy to design with). For one component, there is an AJAX request to query an external server. The issue is, I want to cache these responses for a certain period of time only if they are successful.

Laravel has the Cache::remember() function, but the issue is there seems to be no "failed" mode (at least, none described in their documentation) where a cache would not be stored.

For example, take this simplified function:

try {
    $server->query();
} catch (Exception $e) {
    return Response::json('error', 400);
}

I would like to use Cache::remember on the output of this, but only if no Exception was thrown. I can think of some less-than-elegant ways to do this, but I would think that Laravel, being such an... eloquent... framework, would have a better way. Any help? Thanks!

like image 402
Connor Peet Avatar asked Oct 18 '25 16:10

Connor Peet


1 Answers

This is what worked for me:

if (Cache::has($key)) {
    $data = Cache::get($key);
} else {
    try {
        $data = longQueryOrProcess($key);
        Cache::forever($key, $data); // only stored when no error
    } catch (Exception $e) {
        // deal with error, nothing cached
    }
}

And of course you could use Cache::put($key, $data, $minutes); instead of forever

like image 55
dwenaus Avatar answered Oct 21 '25 05:10

dwenaus