Laravel 5.1 DB:select toArray()

Seems like you need to cast the stdClass Objects as Array so you can have the structure you are looking for

$result = array_map(function ($value) {
    return (array)$value;
}, $result);

The best solutions looking at performance would be changing method how data is grabbed from database:

// get original model
$fetchMode = DB::getFetchMode();
// set mode to custom
DB::setFetchMode(\PDO::FETCH_ASSOC);
// get data
$result = DB::select($sql);
// restore mode the original
DB::setFetchMode($fetchMode);

Obviously if you want to get all the data as array, it will be enough to change in config/database.php from:

'fetch'       => PDO::FETCH_CLASS,

into

'fetch'       => PDO::FETCH_ASSOC,

and then running only:

$result = DB::select($sql);

will return you multidimensional array instead of array of objects


toArray() method converts collection to an array. Models are converted to arrays too:

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

So, I guess you're doing something wrong. If you want more help, please update you question with all related code.

Also, only Eloquent collections (models) have toArray() method.

To use this method, use Eloquent:

$result = \App\User::all()->toArray();