Laravel 4.2中使用Cache::put存入数组后无法读取,该如何解决?
Hey there, let's dig into why your cache isn't saving and returning false when you try to retrieve that array. I've run into similar issues with Laravel 4.2 before, so here are the most likely fixes to try:
1. Check Your Cache Driver Configuration
First up, the most common culprit here is using the wrong cache driver. If your app/config/cache.php has 'default' => 'array', that's a problem—this driver stores cache only in memory for the current request, meaning it's gone as soon as the page loads.
Switch it to a persistent driver like file (the default for Laravel 4.2) or redis/memcached if you have them set up:
'default' => 'file',
2. Verify Storage Directory Permissions
If you're using the file driver, make sure the app/storage/cache folder has proper read/write permissions for your web server user (usually www-data on Apache/Nginx). Run these commands in your project root to fix it:
chmod -R 755 app/storage chown -R www-data:www-data app/storage # Adjust user/group if needed for your server
3. Clean Up Your Array Syntax
While PHP might parse your current array declaration, it's a bit messy and could cause unexpected issues. Simplify it to the standard short array syntax (Laravel 4.2 requires PHP 5.4+, so this is safe):
$posts = [2365, 2366, 2367, 2368, 2369];
4. Test Basic Cache Functionality
Let's rule out any issues with your business code by testing a simple cache operation. Add this route to app/routes.php and visit it in your browser:
Route::get('/test-cache', function() { // Store a simple value Cache::put('test-key', 'cache is working!', 60); // Immediately retrieve it dd(Cache::get('test-key')); });
If you see cache is working!, your cache system is functional, and the issue is likely in how you're calling it in your code. If not, go back to steps 1 and 2—your configuration/permissions are the problem.
5. Simplify Your Cache Retrieval Method
Your getPostsFromCache method works, but you can make it more reliable (and cleaner) by using Cache::get's built-in default value instead of checking Cache::has first. This avoids any edge cases where has might return false but get could still retrieve the value (rare, but possible):
public function getPostsFromCache($key) { return Cache::get($key, array()); }
Final Check
After making these changes, re-run your original code. If the cache still isn't working, double-check if any other parts of your application are clearing the views-87 key (like a cache flush command or another piece of code that deletes it).
内容的提问来源于stack exchange,提问作者Rizwan Saleem

