0

When I use first() in query builder I get result. See:

public function __invoke($_, array $args)
{

  return MyTable::where('id', 1)->first();
}

However, when I change first() with toArray(), I can not get any result. See:

public function __invoke($_, array $args)
{

  return MyTable::where('id', 1)->get()->toArray();
}

How can I get result for toArray() method?

Even I use toArray() method with get(), it does not work!

When I use with first() method result is like that

{
  "data": {
    "myTableResolver": {
      "column_1": 1,
      "column_2": "XYZ"
    }
  }
}

When I use with toArray() method result is like that

{
  "data": {
    "myTableResolver": {
      "column_1": null,
      "column_2": null
    }
  }
}
oxygen
  • 151
  • 2
  • 3
  • 14

2 Answers2

1

because toArray() method belongs to the collection results that comes from fetching query builder, you should fetch the result using get() method:

  return MyTable::where('id', 1)->get()->toArray();
OMR
  • 11,736
  • 5
  • 20
  • 35
1

I guess the best approach is to do this:

return MyTable::find(1)->pluck('some_column')->toArray();

Using pluck you can filter the columns you want to get.

Also you can use find(1) method instead of where('id', 1).

Alireza A2F
  • 519
  • 4
  • 26
  • I have already used another way. But This is an interesting approach. I will try it next time. Thnks. – oxygen Jun 30 '21 at 07:21