Laravel 5.4 - Cache an array

9.6k views Asked by At

I am trying to cache an array, but for some reason, nothing is added. This is the code:

public static function getEmployees()
    {

        if(!Cache::has('employees')):

            $data      = ['urlPath' => '/employees/directory'];

            $params    = ['fields' => 'jobTitle'];

            $employees = API::callAPI('GET', $data, $params);

            Cache::putMany($employees, 1440);

        endif;

        return Cache::get('employees');

    }

And whey I try to get cached value (array), I am getting null:

dd(Cache::get('employees'));

And this is an array I want to store:

array:2 [▼
  "fields" => array:16 [▶]
  "employees" => array:257 [▶]
]

(I am using db for storing)

2

There are 2 answers

7
Marcin Orlowski On BEST ANSWER

You use putMany() wrong. I bet it'd be sufficient for you need to just use regular put():

Cache::put('employees', $employees, 1440);

but if you want putMany() then you need to prepare source array first, which you are not doing:

$data = [
    'fields' => whateverItComesFrom(),
    'employees' => API::callAPI('GET', $data, $params),
];
Cache::putMany($data, 1440);

EDIT

As other users mentioned in comments, aside from incorrect usage, the DB storage may also contribute to the issue as, depending on size of the data you want to cache, it may simply exceed database type limits, i.e. BLOB is just 65535 bytes (64KB) (which suffices for most cases, but you have 200+ entries in array...). MEDIUMBLOB is 16777215 bytes (16 MB) and LONGBLOB for 4294967295 bytes (4 GB), so it may be worth checking that aspect too and change column type if needed.

0
Sasha On

I have found the issue - the limit of the text field was the reason why cache didn't work. Change the type to LONGBLOB (thanks num8er for advice), and now it is working.