6

I try for some time to use an array instead of a collection, as Laravel does.

I tried to do this method, without success:

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});

As explained on https://laravel.com/docs/5.4/upgrade#upgrade-5.4.0, but it's not working...

I also tried to do this:

DB::table('users')->where([...])->take(1)->get()->toArray();

But it's doing:

Array ( [0] => stdClass Object ( [uid] => 1 [...]) )

I know there is more about it on the forum, but they are all outdated.

Thanks

3 Answers 3

6

toArray is changing the collection of objects into an array of objects, like it should. If you want the objects inside the collection to also be arrays, you need to first convert each object:

$collection = DB::table('users')->where([...])->take(1)->get();

$array = $collection->map(function($obj){
  return (array) $obj;
})->toArray();

To use this function in your whole app, you could add a collection macro in the boot method of one of your service providers:

Collection::macro('toArrays', function () {
  return $this->map(function ($value) {
    return (array) $value;
  })->toArray();
});

And this at the top of the file of the service providers:

use Illuminate\Support\Collection;

Then anywhere you get a set of DB results you can just call toArrays on it:

DB::table('users')->where([...])->get()->toArrays();
Sign up to request clarification or add additional context in comments.

7 Comments

Is there a way to do it just once for the whole site, because, I'd just like to use that.
see my edit for a simple way to use this function on any collection in your app @KarylLamoureux
Thank you, just a little thing, now it's Array ( [0] => Array ( [uid] => 1 [...]) ). Is it a way to remove the first array ? to just have Array ( [uid] => 1 [...]) in the macro ? @Jeff
when you use take(1)->get() it still returns a collection. You need to use first() if you want a single object as the response, see @Alexey's answer for that.
I have replace take(1)->get() with first() and it said: Call to undefined method stdClass::toArrays()
|
0

Since you're getting just one object, use the first() method:

$object = DB::table('users')->where([...])->first();
$array = (array)$object;

2 Comments

Good answer, I didn't notice he was only taking 1. You might need to typecast it rather than call toArray() because it is just a basic object
@Jeff yes, I've just tested it and updated the answer at the same time you've commented. OP needs to use (array) casting. Thanks.
0

You can use Laravel Collection's map method to turn each object into an array.

Comments