In this article, I am showing how to get all column names with column types using laravel. Also sharing other ways too.
Example: 1
Schema Facade
// Using Schema Facade
$columns = \Schema::getColumnListing("users");
#Output-1
[
"created_at",
"email",
"id",
"image",
"password",
"password_reset_token",
"phone",
"remember_token",
"role_id",
"social_provider",
"status",
"updated_at",
"username"
]
Example: 2
Using Raw Query
// SQL raw query will return all column names
$query = "SHOW COLUMNS FROM $table_name";
$data['columns'] = \DB::select($query);
#Output - 2
{
"columns": [
{
"Field": "id",
"Type": "bigint unsigned",
"Null": "NO",
"Key": "PRI",
"Default": null,
"Extra": "auto_increment"
},
{
"Field": "role_id",
"Type": "bigint unsigned",
"Null": "NO",
"Key": "",
"Default": "3",
"Extra": ""
},
{
"Field": "username",
"Type": "varchar(191)",
"Null": "NO",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "email",
"Type": "varchar(191)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "phone",
"Type": "varchar(191)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "image",
"Type": "varchar(191)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "social_provider",
"Type": "varchar(191)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "password",
"Type": "varchar(191)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "password_reset_token",
"Type": "varchar(191)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "status",
"Type": "tinyint",
"Null": "NO",
"Key": "",
"Default": "1",
"Extra": ""
},
{
"Field": "remember_token",
"Type": "varchar(100)",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "created_at",
"Type": "timestamp",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "updated_at",
"Type": "timestamp",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
}
]
}
Another way to get columns using DB Schema Facade
// Through DB Facade
$columns = \DB::getSchemaBuilder()->getColumnListing("users");
// or
$columns = \DB::connection()->getSchemaBuilder()->getColumnListing("users");
Hope, this will help you to get all columns. Thank you for your time.
Subscribe to the Email Newsletter