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?