Alfonso Embid-Desmet
Alfonso Embid-Desmet

Reputation: 3622

Cannot create new tables on the fly with Eloquent

I am using Eloquent with SlimPHP and Capsule as DB 'Facade'.

Right now I am just giving support to MySql as I need to create tables on the fly, so I am trying to build two queries and run them.

DB::raw($create_table_statement);
DB::raw($add_keys_statement);

When doing

var_dump($create_table_statement);
var_dump($add_keys_statement);

To see how the queries have been built they are like this:

string(351) "CREATE TABLE IF NOT EXISTS `responses_44` (`id` int(11) NOT NULL AUTO_INCREMENT,`field_20` varchar(150),`field_21` varchar(150),`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',`form_id` int(11) NOT NULL,primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"

string(158) " ALTER TABLE `responses_44` ADD KEY `form_id` (`form_id`), ADD CONSTRAINT `responses_44_ibfk_1` FOREIGN KEY (`form_id`) REFERENCES `forms` (`id`);"

By testing the queries directly onto MySql they get executed with no errors and the table created, however when applied to DB::raw, no error is thrown, and DB::getQueryLog() doesn't show them.

What can be happening?

Thanks

Upvotes: 2

Views: 618

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

DB::statement($create_table_statement);

This is all you need. DB::raw doesn't run anything, it is just a wrapper that is never bound by the builder, instead it is passed to the query in raw form, without escaping anything.

You can use ? placeholders and pass 2nd param with bindings to the statement method as well.

Upvotes: 1

Related Questions