Posted in Laravel

Converting object values to array values

Laravel query returns values as objects. When you need to convert it into array values, you can use any one of the following:

Method 1: Using PHP’s array_map function

$db_results = array_map(function($result){
    return (array) $result;
}, $db_results);

Method 2: Using PDO’s flag in setFetchMode

$defaultFetchMode = DB::getFetchMode();
$data = DB::table('table_name')->get();

You can simply use:

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

But this will modify global fetch mode and not with just this query. To make changes only to a particular instance you can backup the fetch mode before modification and then revert back to original state.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s