Eloquent FETCH_ASSOC


#1

Hello,

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?

Thank you, Appreciate any help.


#2
->toArray()

… should do the trick. Perhaps show a little more of your code?


#3

Hello,

I have tried toArray() and that doesn’t seem to do the trick unfortunately.

$this->c_obj_db_handle->table('users')->where('username',$this->c_username)->get()->toArray()

This is an example of what I would do, It still returns an object.


#4

What does this show?

$result = $this->c_obj_db_handle->table('users')->where('username',$this->c_username)->get()->toArray();
echo gettype($result);

#5

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);
});

Usage:

$db = $this->get('db');
$rows = $db->table('information_schema.schemata')->get()->toArray();

#6

@odan , Thank you!

Is changing it through Dispatcher bad practice or is it perfectly accepteable?

@tflight, Not at home right now but will let you know once i’ve tried it.


#7

Personally, I don’t like this official “workaround” because:

  1. Unnecessarily couples DB component to Events for basic functionality
  2. It will slow down the queries
  3. 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.