Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ottopilot's avatar

Any way to configure PDO::FETCH_ASSOC?

I'm in the middle of a project originally started on 5.2.

I prefer to use the query builder and am NOT using Eloquent (nor will I ever).

I also prefer the query builder to return simple arrays, not arrays of stdClass objects, nor collections because again, I prefer to work with simple arrays.

I originally added:

'fetch' => PDO::FETCH_ASSOC

to config/database.php and have been working with simple arrays successfully for months. I upgraded to 5.4, which includes the change in 5.3 that apparently modified the query builder to return a collection.

The 5.3 upgrade guide said if I wanted the query builder to continue to return arrays I could chain the add() method to the end of each DB query. An annoying inconvenience, but doable...or so I thought. When I do that, I now get an array of stdClass objects, and not an array of simple arrays as I expect.

I've searched all over, and the usual answers are "can't be done" and "why would you want to do that?", neither of which answer my question, which is:

How do I get the query builder in 5.3 or 5.4 to return simple arrays again?

0 likes
5 replies
ottopilot's avatar

Thanks for the link.

I fixed it on my own.

Contrary to the docs / upgrade guide, chaining all() does NOT produce a backward-compatible solution. Chaining all() to the end of my queries outputs an array of stdClass objects, which is not what I need.

To fix this I compared the database connection-related code in 5.2 and 5.4. I saw Taylor removed the line that pulled the fetch mode from the configuration.

The easiest solution was to manually change the fetchMode property in Illuminate/Database/Connection.php to:

PDO::FETCH_ASSOC

This produces an output equivalent to my 5.2 environment -- an array of arrays. Of course now I'll have to remember to do that on every upgrade of the framework, but that will be faster and easier than convincing Taylor to be more flexible.

3 likes
ottopilot's avatar

Yes, it's the framework source, and well aware that I shouldn't modify it, but I have a job to do. I don't have the luxury of accepting every breaking change pushed onto this framework.

4 likes
cnanney's avatar

Another downside of needing to set the fetch mode via event listener (as is the recommended way to fix this from the docs), you lose it when mocking events in unit tests.

Event mocking is all or nothing in tests, as soon as you want to mock and test one event, your new setFetchMode event will then not be fired.

Still looking for elegant solution to this besides editing the source.

1 like

Please or to participate in this conversation.