42

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...

)

13 Answers 13

59

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Good Idea! Are you sure Eloquent does not provide a function to do it?
Eloquent does it, but you are using Query Builder , not Eloquent
$result = array_map(fn($x) => (array)$x, $result);
34

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

6 Comments

This is really advanced. Thanks.
I've found this answer related to this topic, I think this can improve what @Marcin suggest. stackoverflow.com/a/19369644/2848140
I get this error in Laravel 5.4: Call to undefined method Illuminate\Database\MySqlConnection::getFetchMode().
I got this error in Laravel Framework 8.26.1 -- Call to undefined method Illuminate\Database\MySqlConnection::setFetchMode()
This solution no longer works after Laravel 5.4 apparently.
|
13

Here is another approach that is worth to be mentioned:

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

1 Comment

This's only the way around other than listen on even lister laravel,so sad lah.
11

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

9 Comments

$result = DB::select($sql)->toArray();
exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function toArray() on array' in ...
@YevgeniyAfanasyev, I guess that's the answer for aimee's code. Of course it will not work. Please show your code and I'll show you how you can convert it to an array.
I extended the question, I put example there. Thanks.
@YevgeniyAfanasyev, I've updated my answer with working Eloquent code equivalent to $result = DB::select('select * from users');
|
4

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?

Comments

4

you can try this

DB::table('commune')->where('Commune','<>', 'ND')->orderBy('Commune')->get()->pluck('Commune');

Comments

1

You can make a collection in order to use toArray(), very simple approach:

$result = DB::table('users')->get();
$data = collect($result)->map(function($x){ return (array) $x; })->toArray(); 

1 Comment

The accepted answer uses the same concept of array_map-ing, but without extra conversion to and out from collection. I'm afraid you have not contributed much.
0

Good to pick through the answers here to understand the reasons. Here's my version that I settled on:

$users = collect($users) // turn the top level array into a collection
    ->map(fn($user) => (array) $user) // cast each object to an array
    ->toArray(); // convert top level collection back to an array

You had an array of objects. Now you will have an array of arrays. Note that this doesn't do a recursive conversion of the internal array, but since it's only one level deep you're fine.

Comments

-1

Try this

$result = DB::select($sql);
$arr = [];
foreach($result as $row)
{
    $arr[] = (array) $row;
}

4 Comments

This is wrong. I got: local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function get() on array'
UPDATE exception 'ErrorException' with message 'call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'selectRaw''
@huuuk, select accepts not only column names: $users = DB::select('select * from users where active = ?', [1]); - Also, your examples doesn't work. To make last one get something, you need to remove ->get()
@AlexMezenin I'm sorry, I was wrong. You are right. I'm a bit confused wit Eloquent
-1

You can do this way..

At the top

use DB;
use PDO;

--------------------

DB::setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode as array

$result = DB::select('select * from users');

For example, now you can get result like this way.

$first_email = $result[0]['email'];

Now you can change to default fetch mode.

DB::setFetchMode(PDO::FETCH_CLASS);

Comments

-1

One tricky and simple way :

//Got array in stdClass converting to JSON
$temp1= json_encode($result);


//JSON to Array
$temp2= json_decode($temp1,1);`

May be it will help you

1 Comment

I answered the same way on May 30 '16 at 5:44. You are a bit late. Please read existing answers before posting yours.
-2

You can use this one. It's worked for me.

$query = DB::table('user')->select(['id','name'])->get();
$userlist = $query->toArray();

Comments

-4

Easiest way is using laravel toArray function:

public function toArray()
{
    return array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $this->items);
}

1 Comment

toArray() is method, not just function. And it converts collection to an array. I don't have a collection for starters, I have an array of objects. Only because DB::select($sql); returns array of objects. So your answer is not help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.