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

carpad88's avatar

Get column names from table

I want to retrieve all the column names from one table in my DB, I've used this code and it works

        $headings = DB::connection()
            ->getSchemaBuilder()
            ->getColumnListing('colaborators');

The problem is that the column list is ordered alphabetically, but I don't want that I want them in the order they appear in the table.

Someone can help with a workaround for this?

0 likes
4 replies
Dunsti's avatar

when I try this, I get the order like it is in the table:

>>> DB::connection()->getSchemaBuilder()->getColumnListing('users')
=> [
     "id",
     "username",
     "email",
     "password",
     "role_id",
     "remember_token",
     "created_at",
     "updated_at",
     "email_verified_at",
   ]

don't know, why yours is different

2 likes
carpad88's avatar

@dunsti Neither I know, Yesterday I was using that to set up the headings to export the content table to excel, but when I opened the excel I realized the headings doesn't correspond with the right columns, I tried with other model and always I got the columns ordered.

Today I gave another try and seems to work just fine, I don't know why I was getting ordered columns.

carpad88's avatar

@sogeniusio I didn't know what the problem was because actually the code I was using was right.

Please or to participate in this conversation.