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)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
@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]);
Please or to participate in this conversation.