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();
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('table_name')->get();
DB::setFetchMode($defaultFetchMode);

You can simply use:

DB::setFetchMode(PDO::FETCH_ASSOC);
$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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s