phplaravellaravel-8laravel-migrationslaravel-schema-builder

How to use variables instead of column names for running new Migrations directly in the Controller


I'm using Laravel 8 and I wanted to run this code which insert two new columns, if the attribute name does not exist in the returned results of product_attr_info_correction column names.

    $allAttrs = Attribute::all();
    $columns = Schema::getColumnListing('product_attr_info_correction'); 

    for($i=0;$i<count($allAttrs);$i++){
        foreach($columns as $column){
            if(!empty($allAttrs[$i]->name)){
                if(str_contains($column,$allAttrs[$i]->name)){
                    continue;
                }else{
                    $columnName = "product_".$allAttrs[$i]->name."_attr_correction";
                    $columnName2 = "product_".$allAttrs[$i]->name."_attr_rejecting_reason";
                    
                    Schema::table('product_attr_info_correction', function($table)
                    {
                        global $columnName;
                        global $columnName2;
                        
                        $table->tinyInteger($columnName)->default(1)->comment('confirmed = 1 , not confirmed = 0')->after('product_id');
                        $table->string($columnName2)->nullable()->after($columnName);
                    });
                    dd(1);
                }
            }else{
                continue;
            }
        }
    } 

Now it works fine and clean except the database column creation part which returns this error:

SQLSTATE[42000]: Syntax error or access violation: 1166 Incorrect column name '' (SQL: alter table product_attr_info_correction add tinyint not null default '1' comment 'confirmed = 1 , not confirmed = 0' after `product_id`, add varchar(255) null)

However if I replace $table->tinyInteger($columnName)->... with $table->tinyInteger('column_name_example')->..., it works correctly and create a new column.

This means that the variable $columnName & $columnName2 can not be called here somehow.

So I would really appreciate if you tell me how to call a variable instead of a particular name as column name when we want to insert a new one directly in the Controller?


Solution

  • global $columnName;
    global $columnName2;
    

    The above line won't work since they are those variables which are available globally and doesn't reside inside a namespace. The above line made PHP to check inside global namespace and didn't find anything as such. Hence, you got that SQL error where the value of the injected variables went blank or NULL.

    To fix this, you can inject these variables in that function callback itself using use keyword like below:

    function($table) use($columnName, $columnName2){