Convert laravel object to array

Your Friend picture Your Friend · Oct 3, 2014 · Viewed 170.6k times · Source

Laravel output:

Array
(
    [0] = stdClass Object
    (
        [ID] = 5

    )

    [1] = stdClass Object
    (
        [ID] = 4

    )

)

I want to convert this into normal array. Just want to remove that stdClass Object. I also tried using ->toArray(); but I get an error:

Call to a member function toArray() on a non-object.

How can I fix this?

Functionalities have been Implemented on http://www.srihost.com

Answer

Jarek Tkaczyk picture Jarek Tkaczyk · Oct 3, 2014

UPDATE since version 5.4 of Laravel it is no longer possible.

You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

DB::setFetchMode(PDO::FETCH_ASSOC);

// then
DB::table(..)->get(); // array of arrays instead of objects

// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);

For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

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