Convert laravel object to array Convert laravel object to array laravel laravel

Convert laravel object to array


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);// thenDB::table(..)->get(); // array of arrays instead of objects// of course to revert the fetch mode you need to set it againDB::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(...);});


foreach($yourArrayName as $object){    $arrays[] = $object->toArray();}// Dump array with object-arraysdd($arrays);

Or when toArray() fails because it's a stdClass

foreach($yourArrayName as $object){    $arrays[] =  (array) $object;}// Dump array with object-arraysdd($arrays);

Not working? Maybe you can find your answer here:

Convert PHP object to associative array


Just in case somebody still lands here looking for an answer. It can be done using plain PHP. An easier way is to reverse-json the object.

function objectToArray(&$object){    return @json_decode(json_encode($object), true);}