Storing Arrays in Redis: Moving Beyond set
You have successfully configured your Redis connection within Laravelâs config/database.php. You are comfortable using the Redis::connection() facade to store scalar values. The pattern is familiar and straightforward: you use $redis->set('name', 'Test') to write and $redis->get('name') to read a single string. This works because Redis primitives are primarily strings.
However, a common stumbling block arises when attempting to store an array directly into that same key using the set method. Attempting to pass an array object directly to $redis->set('name', $array) triggers a fatal error: strlen() expects parameter 1 to be string, array given.
This error occurs because the underlying PHP Redis extension does not automatically serialize data types like arrays into the binary format required by Redis before sending the command. The set command strictly expects a string value. When you pass an array, the extension fails immediately during the serialization attempt within its own codebase. It is not a limitation of your application logic; it is a strict requirement of the protocol and the PHP client library that Redis values must be strings.
To resolve this, you must explicitly serialize your data before passing it to Redis. In Laravel, the most idiomatic way to handle this is by leveraging the json_encode function or relying on the collection methods provided by the Redis facade if available in your specific version.
If you are working with a simple indexed array like [5, 10], converting it to a JSON string is the standard approach:
$redis = Redis::connection();
$data = ['value' => 5, 'count' => 10];
$jsonData = json_encode($data);
$redis->set('user_stats', $jsonData);
To retrieve the data later, you must decode the string back into an array:
$retrievedJson = $redis->get('user_stats');
$data = json_decode($retrievedJson, true); // true converts object to array
This approach treats the array as a single opaque string blob inside Redis. It is robust, version-independent, and works seamlessly with PHPâs native type handling.
You might encounter alternative suggestions involving Redis-specific data structures like Lists or Hashes. For instance, you might see code attempting to use lrange to retrieve multiple values. The source material highlights an error where $redis->lrange('names', array(5, 10)) is used to mimic array storage. This is conceptually different from storing a single array. Lists (lrange) store ordered collections of strings, whereas your original goal was likely to store a structured dataset as a single entity. Using lrange requires you to push individual elements onto the list using rpush, which changes the data model entirely.
If you attempt to use $redis->command('lrange', array(5, 10)), you encounter the error 'command' is not a registered Redis command. This happens because the PHP Redis extension does not expose raw commands via a generic command method in older versions or specific configurations. Instead, it provides specific methods for specific data types (lpush, lrange, hset, etc.). If you need raw command execution, you would typically use $redis->rawCommand('LRANGE', ['key', 'start', 'stop']). However, this is an advanced technique and should only be used when necessary.
When choosing between JSON serialization and Redis data structures, consider your access patterns. If you frequently query individual fields within the stored data (e.g., getting just the count without reloading the whole object), a Hash (hset) might be more performant. However, if you treat the entire array as a single unit for caching or passing between services, JSON serialization via set is simpler and less error-prone.
For developers working with Laravel's ecosystem, ensuring your Redis driver is correctly configured in config/database.php remains critical. Always verify that the driver key points to 'redis' and that the connection host and port match your server setup. Once these fundamentals are in place, handling complex data types simply requires remembering that Redis speaks strings, so you must speak its language by encoding your arrays accordingly.