bart's avatar
Level 13

Query builder returns an array

Hey everybody,

I like to do a query using the query builder like this:

$invoices = DB::table('invoice')->get();

But this returns an array of standard objects, why? I'm expecting a collection.

Any idea about that? Thanks a lot guys!

0 likes
6 replies
JarekTkaczyk's avatar

@bart Yes, query builder returns array of standard objects. Always been like this. There was try to make it a collection once, but it didn't get through.

bart's avatar
Level 13

Thanks @JarekTkaczyk and @mstnorris for your responses. The main problem that caused me to open this thread was an error when returning the result:

The Response content must be a string or object implementing __toString(), "boolean" given.

In my opinion I have to get a JSON response. I did try it out with an Eloquent model, too with the same result. What I did then did the trick: I whitelisted some fields using the protected $visible variable. Et voila.

So maybe it's a database/connection encoding issue which crashes the JSON returning.

Nevertheless adding an array of returning fields to the query builder get() method will result in a JSON response on return.

mstnorris's avatar

Well you need to be returning something so maybe you weren't returning anything, i.e. you'd hidden them all. I couldn't say without looking at your code.

bart's avatar
Level 13

As I told you the problem is maybe a fields content problem. It has absolutely nothing to do with the model. But I don't need all fields, so selecting them in the get() method (or adding a ->select([fields])) does the trick.

Please or to participate in this conversation.