zagreus's avatar

Get raw results - not a collection from Query Builder

When I run a query in mysql I get a table, and what Laravel does is turn that into a collection for me. Most of the time that's amazing, great. However, I would like to build a query and get the original table back in PHP because I'm going to return the table (for reporting purposes).

It seems like a waste of processing power to query -> convert to collection -> flatten back to the array and return it.

So instead of results like this:

[
      "name" => "Main Table",
      "seat_number" => 1,
      "id" => "01hca0hshxs8dbw6ft3vpymyrr"
  ],
...

I want the original results like this:

["Main Table", 1, "01hca0hshxs8dbw6ft3vpymyrr"],
...

I can't work out how to get the raw table results from my SQL query in Laravel. Any suggestions/help would be much appreciated.

0 likes
2 replies
s4muel's avatar
s4muel
Best Answer
Level 50

either use raw sql query:

$rows = DB::select("SELECT * FROM users");
dump($rows);

or play around with cursors (https://laravel.com/docs/10.x/eloquent#cursors), but it uses LazyCollection, so it "processes" it somehow anyway, but afaik does not create a model instance (not sure, you need to tinker a bit):

$rows = DB::table('users')->cursor();

foreach ($rows as $row) {
    //row is an array
    dump($row);
}

1 like

Please or to participate in this conversation.