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

Time:06-05

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

CodePudding user response:

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();

CodePudding user response:

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.

  • Related