Skip to content
Advertisement

Return values only (no keys/associative array) in Laravel

Situation

I have the following code to get all data as an array:

JavaScript

This will return the data in the following format:

JavaScript

But I want only the values as a regular array (no keys/associative array) so the array is not converted to an object when I convert it to JSON:

JavaScript

Inadequate solutions

I know I can convert this with a loop and use array_values(), but the former is not a one liner while the second works only for one level and not for arrays of arrays.

Also I’m looking for a way to “configure” Eloquent/Query Builder, and not a method to convert the once returned results.

Questions

Is there a setting or a way I can do this with Eloquent/Query Builder?

Advertisement

Answer

TL;DR

Just tell PDO to work this way:

JavaScript

Don’t forget to set back the default value or whatever was your previous setting. Also you will need to use these facades:

JavaScript

In details (behind the scenes)

This is controlled via the underlying PDO itself, that can by controlled via fetch_style. The constant we need is this one:

PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

Now we just have to pass this in a Laravel way. This constant is passed to PDO in the Illuminate/Database/Connection.php file in the select() function’s last line with a help of a getter:

JavaScript

Off course there is a public setter too: setFetchMode(), so we just have to receive the connector and we can set it. According to the documentation:

When using multiple connections, you may access each connection via the connection method on the DB facade.

So we have everything to do this:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement