Stas Coder
Stas Coder

Reputation: 347

Laravel 5 cache query - get result as associative array

I want to cache query and get result as associative array. When I do it without caching like this, it's okay:

class ItemRepositoryEloquent {

    public function getItems() {

        $items= Item::lists('word','key');

        return $items->toArray();

    }

}

But when I try to cache my query like this:

class ItemRepositoryEloquent {

    public function getItems() {

        $items = Cache::remember('items', 1440, function(){
            return Item::lists('word','key');
        });

        return $items->toArray();

    }

}

It returns result like this:

[
    0 => array('key' => 'word')
    1 => array('key' => 'word')
    2 => array('key' => 'word')
    3 => array('key' => 'word')
    4 => array('key' => 'word')
    5 => array('key' => 'word')
]

But I want the result to be like this after caching:

[
    'key' => 'word',
    'key' => 'word',
    'key' => 'word',
    'key' => 'word',
    'key' => 'word'
]

Thanks in advance.

Upvotes: 0

Views: 1227

Answers (1)

Mark Davidson
Mark Davidson

Reputation: 5513

You should be able to get the result your looking for by using the collapse method not sure what remember returns by default but here is an example working with a raw array

$collection = collect([                                                                                                                                                 
    0 => array('key1' => 'word'),                                                                                                                                           
    1 => array('key2' => 'word'),                                                                                                                                           
    2 => array('key3' => 'word'),                                                                                                                                           
    3 => array('key4' => 'word'),                                                                                                                                           
    4 => array('key5' => 'word'),                                                                                                                                           
    5 => array('key6' => 'word'),                                                                                                                                       
]);

then you can do

$collection->collapse()->toArray();

which will give you

[
     "key1" => "word",
     "key2" => "word",
     "key3" => "word",
     "key4" => "word",
     "key5" => "word",
     "key6" => "word",
]

Upvotes: 1

Related Questions