1

I'm trying to initialize eloquent with setFetchMode as PDO::FETCH_ASSOC.

I've tried everything possible but it doesn't work.

What I tried so far :

To add it using the addConnection

$capsule = new Illuminate\Database\Capsule\Manager;

$capsule->addConnection([
    ...
    'fetch' => PDO::FETCH_ASSOC
]);

Using setFetchMode

$capsule->setFetchMode(PDO::FETCH_ASSOC);

Using events :

$t = new Illuminate\Events\Dispatcher;
$t->listen(Illuminate\Database\Events\StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(PDO::FETCH_ASSOC);
});

But none of these work. Any idea how to make PDO::FETCH_ASSOC work?

PS : I'm aware the first two options do not work with the recent version of eloquent, but I had to give it a try nonethless. I'm open to suggestions tho on how to make the third option work. Normally, the third one should start by looking like this Event::listen, but I don't know where is that Events class is coming from. Also do I need some sort of event listener?

PPS : I'm not using Laravel, I'm using illuminate's eloquent with PHP using composer.

1 Answers1

1

Install the illuminate/events package and use this:

use Illuminate\Container\Container;
use Illuminate\Database\Capsule\Manager;
use Illuminate\Database\Events\StatementPrepared;
use Illuminate\Events\Dispatcher;

$capsule = new Manager;
$capsule->addConnection([...]);

$dispatcher = new Dispatcher(new Container);
$capsule->setEventDispatcher($dispatcher);

$dispatcher->listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(PDO::FETCH_ASSOC);
});
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
  • I'll be trying this and I'll get back to you, thanks! –  Mar 26 '19 at 11:01
  • does this answer really do something different to this one: https://stackoverflow.com/a/44916109/1247113 ? I'm currently using the `DB` facade, so I have no idea what I would have to add instead of the `[...]` in `addConnection`... – rob74 May 28 '21 at 08:30
  • 1
    @rob74 The other answer is for Laravel users, this one for standalone users of the database package. – Jonas Staudenmeir May 29 '21 at 14:51
  • I completely missed that this question only referst to Eloquent, not to Laravel as a whole, sorry for that! – rob74 Jun 01 '21 at 12:41