I have decided to use Eloquent for a little project of mine, I want queries to come back as an Associative Array instead of an Object.
I have tried ->get()->toArray() , but this does not seem to be doing the trick.
Are there any settings I can change to make all queries to be in an Array?
I have tried - $capsule->setFetchMode(PDO::FETCH_ASSOC); but this doesn’t seem to work either.
At the minute I am doing json_decode(json_encode)) but this seems a little messy?
In Laravel 5.4, the public setter and config option for PDO fetch mode was removed, and defaults to PDO::FETCH_OBJ. The only global way to change this is to now rely on events.
Installation:
composer require illuminate/events
Then register this event handler in your container:
$dispatcher = new \Illuminate\Events\Dispatcher();
$db->setEventDispatcher($dispatcher);
$dispatcher->listen(\Illuminate\Database\Events\StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(PDO::FETCH_ASSOC);
});
Personally, I don’t like this official “workaround” because:
Unnecessarily couples DB component to Events for basic functionality
It will slow down the queries
Events are a poor workaround for this, as mocking an event for testing will then prevent the fetch mode event from firing, and if your app relies on a different fetch mode you now have problems with your tests.
For these reasons, there is also a proposal on Github and some other issues like this.
Unfortunately, there are no good alternatives. e. g. a custom converter or so. I hope that setFetchMode will be back one day.
Personally i use a wapper class wich extends \Illuminate\Database\MySqlConnection.
Just define a resolver and return your wrapper class, you are good to go.