[php] Convert laravel object to array

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

This question is related to php arrays laravel laravel-4 laravel-3

The answer is


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

If you want to get only ID in array, can use array_map:

    $data = array_map(function($object){
        return $object->ID;
    }, $data);

With that, return an array with ID in every pos.


It's also possible to typecast an object to an array. That worked for me here.

(array) $object;

will convert

stdClass Object
(
    [id] => 4
)

to

Array(
    [id] => 4
)

Had the same problem when trying to pass data from query builder to a view. Since data comes as object. So you can do:

$view = view('template', (array) $object);

And in your view you use variables like

{{ $id }}

this worked for me:

$data=DB::table('table_name')->select(.......)->get();
$data=array_map(function($item){
    return (array) $item;
},$data);

or

$data=array_map(function($item){
    return (array) $item;
},DB::table('table_name')->select(.......)->get());

I suggest you simply do this within your method

public function MyAwesomeMethod($returnQueryAs = null)
{
    $tablename = 'YourAwesomeTable';

    if($returnQueryAs == 'array')
    {
        DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
    }

    return DB::table($tablename)->get();
}

With this all you need is to pass the string 'array' as your argument and Voila! An Associative array is returned.


You need to iterate over the array

for ($i = 0, $c = count($array); $i < $c; ++$i) {
    $array[$i] = (array) $array[$i];
}

ans use (array) conversion because you have array of objects of Std class and not object itself

Example:

$users = DB::table('users')->get();

var_dump($users);

echo "<br /><br />";

for ($i = 0, $c = count($users); $i < $c; ++$i) {
    $users[$i] = (array) $users[$i];
}
var_dump($users);
exit;

Output for this is:

array(1) { [0]=> object(stdClass)#258 (8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }

array(1) { [0]=> array(8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } } 

as expected. Object of stdClass has been converted to array.


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

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

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

Not working? Maybe you can find your answer here:

Convert PHP object to associative array


You can also get all the result always as array by changing

// application/config/database.php

'fetch' => PDO::FETCH_CLASS,
 // to
'fetch' => PDO::FETCH_ASSOC,

Hope this will help.


$foo = Bar::getBeers(); $foo = $foo->toArray();


Its very simple. You can use like this :-

Suppose You have one users table and you want to fetch the id only
$users = DB::table('users')->select('id')->get();
$users = json_decode(json_encode($users)); //it will return you stdclass object
$users = json_decode(json_encode($users),true); //it will return you data in array
echo '<pre>'; print_r($users);

Hope it helps


this worked for me in laravel 5.4

$partnerProfileIds = DB::table('partner_profile_extras')->get()->pluck('partner_profile_id');
$partnerProfileIdsArray = $partnerProfileIds->all();

output

array:4 [?
  0 => "8219c678-2d3e-11e8-a4a3-648099380678"
  1 => "28459dcb-2d3f-11e8-a4a3-648099380678"
  2 => "d5190f8e-2c31-11e8-8802-648099380678"
  3 => "6d2845b6-2d3e-11e8-a4a3-648099380678"
]

https://laravel.com/docs/5.4/collections#method-all


Object to array

$array = (array) $players_Obj;  

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

Output:

array(2) {
    'foo' => int(1)
    'bar' => int(2)
}

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

$res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();

I use get(), it returns an object, I use the attributesToArray() to change the object attribute to an array.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to laravel-3

Convert laravel object to array Laravel - Pass more than one variable to view My Routes are Returning a 404, How can I Fix Them?