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

ArchStanton's avatar

Create a column if it does not exist

I am trying to test an array to see if they exist in they table as column names, If they don't I want to create them.


$metrics = ['total', 'average_age', 'total_age']

foreach($metrics as $metric) {
  
\Schema::table('postInsightsData', function($table, $metric)
{
    $table->string($metric->column_name);
});
}

```

The first problem is I cannot pass the array into the Schema create method. Any 

0 likes
5 replies
primordial's avatar
Level 7

@ArchStanton Are you trying to modify your DB schema on-the-fly as part of application logic?

Pass data using "use"

function($table, $metric) use( $variable) {

You can test for the existence of a column using

    $column = $table->hasColumn('my_column');

    if ($column) {
        // do something
    }
1 like
ArchStanton's avatar

@primordial

Looks good although I can't call the method

Call to undefined method Illuminate\Database\Schema\Blueprint::hasColumn()
willvincent's avatar

hasColumn() belongs to the schema builder class.

It also requires you pass the table name to it.

Proper usage would be like this:

Schema::hasColumn('table_name', 'foo');

Better bet though might be to use the getColumnListing method and intersect it with the list of columns you want to check existence of..

$columns = Schema::getColumnListing('table_name');
9 likes

Please or to participate in this conversation.