Laravel 5.1 DB:select toArray()
I have a large SQL statement that I am executing like so:
$result = DB::select($sql);
For example
$result = DB::select('select * from users');
I'd like the result to be an array - but at the moment it returns a structure like so, an array with Objects...
Array
(
0 => stdClass::__set_state(array(
'id' => 1,
'first_name' => 'Pavel',
'created_at' => '2015-02-23 05:46:33',
)),
1 => stdClass::__set_state(array(
'id' => 2,
'first_name' => 'Eugene',
'created_at' => '2016-02-23 05:46:34',
)),
...etc...
)
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 areEloquent
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();
Here is another approach that is worth to be mentioned:
$resultArray = json_decode(json_encode($result), true);
For laravel/lumen 5.4 (that uses illuminate/database 5.4):
$pdo = DB::getPdo();
$statement = $pdo->prepare($yourQuery);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$results = $statement->fetchAll();
Or listen to Illuminate\Database\Events\StatementPrepared event: Laravel 5.4 - How to set PDO Fetch Mode?