Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - set database.fetch config at runtime

In Laravel 3 I could set the database 'fetch' config at runtime (to get the results as an array rather than an object):

Config::set('database.fetch', PDO::FETCH_ASSOC);

In Laravel 4, the result is still being returned as an object.

What am I doing wrong?

[Edit - extra details]

I decided to test if the config was being set, and also to try identical code segments in Laravel 3 and Laravel 4 side-by-side.

//first fetch as object
Config::set('database.fetch', PDO::FETCH_CLASS);
//Laravel 3 and 4 returns 88 ... expected:
echo PDO::FETCH_CLASS.Config::get('database.fetch');
$users = $users = DB::table('users')->get();
//Laravel 3 and 4 both return an array of objects(stdClass) ... expected
var_dump($users);

//then fetch as array
Config::set('database.fetch', PDO::FETCH_ASSOC);
//Laravel 3 and 4 returns 22 ... expected:
echo PDO::FETCH_ASSOC.Config::get('database.fetch');
$users = $users = DB::table('users')->get();
//Laravel 3 returns an array of arrays ... expected
//Laravel 4 returns an array of objects(stdClass) ... UNEXPECTED!
var_dump($users);
like image 657
mtmacdonald Avatar asked Oct 14 '13 13:10

mtmacdonald


1 Answers

TL;DR: Don't use config for run-time changes

The configuration set's the fetch mode on initialization only. This is generally true for all Illuminate libraries.

If you need to change the fetch-mode in run-time, you need to set this on your connection object rather than in the configuration.

Luckily, we have access to the connection object.

Notice that the Connection object has a setFetchMode() method.

Use the Connection Object Directly

This means in your code you can get your connection and then run setFetchMode(PDO::FETCH_ASSOC) with it prior to querying the DB.

// With Query Builder
$query = DB::connection()->setFetchMode(PDO::FETCH_ASSOC);

// With Eloquent model
$user = new User;
$user->getConnection()->setFetchMode(PDO::FETCH_ASSOC);
like image 180
fideloper Avatar answered Sep 30 '22 04:09

fideloper