Search code examples
phpmysqlsqllaravellaravel-4

Run raw SQL in migration


I'm trying to execute a raw SQL thru a Laravel (PHP) migration execution. 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).


Solution

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

    alter table `users` modify `age` datetime
    

    In this particular case you can omit escaping at all:

    alter table users modify age datetime