Laravel 5: Usage of Table Names in Raw MySQL Queries

Published in category Programming and Productivity
on Christian Mayer's Weblog.

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?

Recent Posts

About the Author

Christian is a professional software developer living in Vienna, Austria. He loves coffee and is strongly addicted to music. In his spare time he writes open source software. He is known for developing automatic data processing systems for Debian Linux.