Support the ongoing development of Laravel.io →
posted 9 years ago
Database
Last updated 1 year ago.
0

You can do this:

$resultArray = json_decode(json_encode($result), true);

But, you know, the best approach is to use Eloquent Models.

Last updated 1 year ago.
0

Try this:

$result = DB::select($sql)->get();
$result = $result->toArray();

The get() will cast it to a Collection, that is a lot more powerful than an array. You can iterate over it and more.

Have a bash at that. Hopefully it should be what you need: http://laravel.com/docs/4.2/eloquent#collections

Last updated 1 year ago.
0
$data = \DB::table('error_reports')
          ->select(array('exception_type', \DB::raw('COUNT(*) as count')))
          ->orderBy('count', 'DESC')
          ->groupBy('exception_type')
          ->take(5)
          ->get();

This yields an array with objects for me. I'd like it to be an array of arrays - or a Collection which I can call toArray() on. Am I doing something wrong? T2theC's post seem to indicate it would be a Collection.

0

do this :

$data =  \DB::table('error_reports')
      ->select(array('exception_type', \DB::raw('COUNT(*) as count')))
      ->orderBy('count', 'DESC')
      ->groupBy('exception_type')
      ->take(5)
      ->get();

$data = collect($data)->map(function($x){ return (array) $x; })->toArray(); 

That will cast each object in the array to an array, and the toArray gets you from the collection back to an array.

Last updated 7 years ago.
0

pixelgremlins said:

$data = collect($data)->map(function($x){ return (array) $x; })->toArray(); That will cast each object in the array to an array, and the toArray gets you from the collection back to an array.

I was having the same issue after returning results from a RAW DB query. This worked for me, thanks!

0

Why don't we just use collect() method?

$data =  \DB::table('error_reports')
      ->select(array('exception_type', \DB::raw('COUNT(*) as count')))
      ->orderBy('count', 'DESC')
      ->groupBy('exception_type')
      ->take(5)
      ->get();
$collection = collect($data);

You can then go ahead and use the toArray() method to convert it to an array convert it to an array if you prefer.

Last updated 7 years ago.
0

dattz said:

$collection = collect($data);

You can then go ahead and use the `toArray()` method to convert it to an array convert it to an array if you prefer.

Nice, I used collect($data)->toArray();

UPDATE: Indeed it still returning objects inside, as @pixelgremlins said, working using collect($data)->map(function($x){ return (array) $x; })->toArray()

Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

netm netm Joined 2 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.