Murata
Murata

Reputation: 21

DB::get is Array in Laravel but it says it is not array

I thought the data which is from DB::get() is Array. However , the console says it is not array.

                $fruitList =  Food::where('id' => 300)->get(['id']);             
                shuffle($fruitList);

ErrorException: shuffle() expects parameter 1 to be array, object given in file

Upvotes: 0

Views: 86

Answers (2)

Enoch
Enoch

Reputation: 1001

Just like @A.seddighi mentioned, using get() or all() gives you a collection. It may seem like an array when you output it using return or print but it is different.

Collections can be filtered, queried and so on. e.g

$fruitList->has('price')

etc.

To get an array simply called the toArray() method on it, you may also use flatMap(), mapWithKeys() etc. Make sure you follow the documentation that is suitable for your version of laravel.

Upvotes: 0

A.Seddighi
A.Seddighi

Reputation: 1765

The return value of get() is not an array. it's Laravel array collection you can convert it to an array or use shuffle of array collection:

$fruitList =  Food::where('id' => 300)->get(['id'])->toArray();             
shuffle($fruitList);

with array collection:

$fruitList =  Food::where('id' => 300)->get(['id'])->shuffle();

Upvotes: 2

Related Questions