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);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With