DB query builder toArray() laravel 4
Asked Answered
A

12

51

I'm trying to convert a query to an array with the method toArray() but it doesn't work for the query builder. Any ideas for convert it?

Example

DB::table('user')->where('name',=,'Jhon')->get()->toArray();
Astred answered 25/12, 2013 at 20:50 Comment(0)
J
66

toArray is a model method of Eloquent, so you need to a Eloquent model, try this:

 User::where('name', '=', 'Jhon')->get()->toArray();

http://laravel.com/docs/eloquent#collections

Jehiah answered 25/12, 2013 at 22:2 Comment(1)
what if I am forced to use Fluent? I need to read thousands of rows which is not efficient with eloquent!!! that give me maximum execution time while Fluent doesn'tLavernelaverock
T
79

If you prefer to use Query Builder instead of Eloquent here is the solutions

$result = DB::table('user')->where('name',=,'Jhon')->get();

First Solution

$array = (array) $result;

Second Solution

$array = get_object_vars($result);

Third Solution

$array = json_decode(json_encode($result), true);
Thallic answered 15/6, 2015 at 7:53 Comment(0)
J
66

toArray is a model method of Eloquent, so you need to a Eloquent model, try this:

 User::where('name', '=', 'Jhon')->get()->toArray();

http://laravel.com/docs/eloquent#collections

Jehiah answered 25/12, 2013 at 22:2 Comment(1)
what if I am forced to use Fluent? I need to read thousands of rows which is not efficient with eloquent!!! that give me maximum execution time while Fluent doesn'tLavernelaverock
B
13

Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

In this case, it might be more efficient to do:

DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
$result = DB::table('user')->where('name',=,'Jhon')->get();

That way, you won't waste time creating objects and then converting them back into arrays.

Boffa answered 23/9, 2015 at 2:47 Comment(2)
The only way to get array of arrays (not array of stdClass objects)Sentinel
This no longer works as of Laravel 5.4.Sobriety
D
9

And another solution

$objectData = DB::table('user')
    ->select('column1', 'column2')
    ->where('name', '=', 'Jhon')
    ->get();
$arrayData = array_map(function($item) {
    return (array)$item; 
}, $objectData->toArray());

It good in case when you need only several columns from entity.

Dilemma answered 30/5, 2016 at 21:19 Comment(1)
need to change $objectData->toArray() for it to worksSynthiasyntonic
P
1

I'm currently on L8 and this is the only way I can find to get this working for a single query. You have to globally set an event callback to FETCH_ASSOC, then right after the query has ran, set it back to FETCH_OBJ (Laravel default).

use Illuminate\Support\Facades\Event;
use Illuminate\Database\Events\StatementPrepared;

Event::listen(StatementPrepared::class, function ($event) {
        $event->statement->setFetchMode(\PDO::FETCH_ASSOC);
    });

$collectionOfArrays = \DB::table('table1')->where(...)->get();

Event::listen(StatementPrepared::class, function ($event) {
        $event->statement->setFetchMode(\PDO::FETCH_OBJ);
    });

If you want FETCH_ASSOC behaviour throughout, then you can just follow the official upgrade guide and place the first listener in the AppServiceProvider.

For my use case, i'm dealing with millions of records, then chunk inserting them into another table via insert() as an array. It made more sense to fetch as an array and update as an array, instead of changing the iterable type along the way (performance is key here).

I'm not aware of any performance caveats with this hack, as it's served me fine so far. It would made sense for Laravel to add proper support for this, but for now i've just made my own helper class to set and revert around the queries I need it to.

Potoroo answered 14/3, 2023 at 11:15 Comment(0)
B
1

User::where('name','Jhon')->get()->toArray();

Boland answered 19/1 at 8:28 Comment(1)
Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?Nystatin
E
0

Tested in Laravel 5.6

The fastest and simple way is just to use json_decode (No need to use json_encode), example:

$records = DB::table('user')->where('name',=,'Jhon')->get();

echo json_decode($records,true);
Endothermic answered 27/5, 2021 at 12:46 Comment(0)
S
0

Query Builder To Array work a round

toArray() For Eloquent ORM:

// Using Eloquent ORM
$users = User::where('name', '=', 'Jhon')->get()->toArray();

toArray() For Query Builder:

// Using Query Builder
$data = DB::table('user')->where('name', '=', 'Jhon')->get();
$users = collect($data)->map(function($x){ return (array)$x; })->toArray();
Suziesuzuki answered 27/9, 2023 at 12:15 Comment(0)
B
0
User::where("fk_role_id",3)->pluck('id')->toArray()
Boland answered 30/12, 2023 at 12:28 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Costanzo
R
-1

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);
Retorsion answered 8/2, 2018 at 10:26 Comment(1)
Objects inside the result set are instances of stdClass so $value->toArray() won't work and this code will do nothing to $resultStationer
S
-2

You can do this using the query builder. Just use SELECT instead of TABLE and GET.

DB::select('select * from user where name = ?',['Jhon']);

Notes: 1. Multiple question marks are allowed. 2. The second parameter must be an array, even if there is only one parameter. 3. Laravel will automatically clean parameters, so you don't have to.

Further info here: http://laravel.com/docs/5.0/database#running-queries

Hmmmmmm, turns out that still returns a standard class for me when I don't use a where clause. I found this helped:

foreach($results as $result)
{
print_r(get_object_vars($result));
}

However, get_object_vars isn't recursive, so don't use it on $results.

Subcartilaginous answered 18/5, 2015 at 13:1 Comment(0)
P
-3

try this one

DB::table('user')->where('name','Jhon')->get();

just remove the "=" sign . . . .because you are trying to array just the name 'jhon' . . . . . . . .I hope it's help you . .

Photochronograph answered 6/10, 2016 at 4:29 Comment(1)
This approach can only get Collection. Not array. The question is asking about toArray()Frap

© 2022 - 2024 — McMap. All rights reserved.