Christian Mayer's Weblog

Laravel 5: Usage of Table Names in Raw MySQL Queries

I came across a Migration Issue while programming with Laravel 5.
See this thread: https://laracasts.com/discuss/channels/general-discussion/l5-migration-issue

But this post isn’t accutally about the issue itself. The problem is that you can’t use a static table name in a raw MySQL statement. Especially if you use dynamic table name prefixes.

This is bad. For Example:

DB::statement('ALTER TABLE `persons` CHANGE `birthday` `birthday` TIMESTAMP NULL;');

This is a better solution:

$tableName = DB::getQueryGrammar()->wrapTable('persons');
DB::statement('ALTER TABLE '.$tableName.' CHANGE `birthday` `birthday` TIMESTAMP NULL;');

Or even better:

$person = new Person();
$tableName = DB::getQueryGrammar()->wrapTable($person->getTable());
DB::statement('ALTER TABLE '.$tableName.' CHANGE `birthday` `birthday` TIMESTAMP NULL;');

But static raw MySQL statements are always bad in a dynamic framework. Why not being dynamically if you can be?

Posted on .
Categories: Programming, Productivity
Tags: PHP, Laravel, Framework, Migration, Issue, Laracasts, dynamic, raw, static, MySQL, SQL, Query, statement

Imprint | Usage | Categories | RSS Feed
Copyright © 2006 by