Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dpower's avatar

Extract field names from a DB::select() query

I'm working on a dynamic CSV generator and I'd like to access the field names I've assigned in my query.

I realize I can access a table's column names with Schema::getColumnListing().

But my custom query results won't use table column names. For instance, if my query looks like this:

SELECT 
   id as customer_id,
   name as customer_name
FROM
   customers

I need to dynamically pick off customer_id, customer_name, etc. from the DB facade.

Is this possible?

0 likes
5 replies
tykus's avatar

The unfinished query can be interrogated, e.g.

$query = DB::table('customers')->select('id as customer_id', 'name as customer_name');
dump($query->columns); // you will need to extract the column alias(es)
1 like
dpower's avatar

@tykus

This is helpful and gives me a few additional threads to pull.

My ultimate desire is to pass a post-query result set to a "dumb" createCsv() function and have it figure out the column / field names and add them as headers to the CSV file. So the function won't have access to the query, just its results.

I appreciate your suggestion!

tykus's avatar

@dpower so long as the query produces a Collection with at least one result:

$customers = DB::table('customers')
    ->select('id as customer_id', 'name as customer_name')
    ->get();
$columns = array_keys((array) $customers->first())
1 like
tykus's avatar
tykus
Best Answer
Level 104

@dpower if you drop down to PDO, you can FETCH_ASSOC so you're already working with an array:

$customers = \DB::connection()
  ->getPdo()
  ->query("SELECT id as customer_id, name as customer_name FROM customers")
  ->fetchAll(\PDO::FETCH_ASSOC);

$columns = array_keys($customers[0]);
1 like
dpower's avatar

array_keys()!!!

Yes, of course. I've used that in other contexts but for some reason didn't think of it here!

Many thanks!

Please or to participate in this conversation.