Milkncookiez Milkncookiez - 2 months ago 15
MySQL Question

Run this raw SQL in migration

Ok, I was trying with whatever syntax and can't think how can I write this correctly:

Schema::table('users', function(Blueprint $table){
$sql = <<<SQL
ALTER TABLE 'users' MODIFY 'age' DATETIME
SQL;
DB::connection()->getPdo()->exec($sql);
});


also tried with
DB::statement('ALTER TABLE \'users\' MODIFY COLUMN DATETIME);


and double quotation marks and so on... I always get the following when I run the migration:


Syntax error or access violation: 1064 You have an error in your SQL syntax; check

the manual that corresponds to your MariaDB server version for the right syntax to use near ''users' MODIFY 'age' DATETIME' at line 1


Yes, I have checked, MariaDB uses MySQL's syntax (at least for this case).

Answer

Use back-ticks instead of single quotes to escape identifiers in MySQL:

Schema::table('users', function(Blueprint $table){
    $sql = 'ALTER TABLE `users` MODIFY `age` DATETIME';
    DB::connection()->getPdo()->exec($sql);
});