Reputation: 367
I am trying to create new mysql tables based on user input in the Laravel Framework.
A user submits a form that is processed in a controller, the form data is saved, and then a NEW table is created based on the user's input (to receive data at a later time).
In laravel tables can be created using schema::create()
Schema::create('newtablename', function($table){
$table->increments('id')->unique(); //primary key
$table->string('columnname');
etc.
});
Essentially I want to do this, except basing the table name and column names on the user's input:
User input is a multidimensional array like this:
$newtableschema = array(
'tablename' => 'tablename',
'colnames' => array('One', 'Two', 'Three', 'Four');
);
Schema::create($newtableschema['tablename'], function($table){
$table->increments('id')->unique(); //primary key
foreach($newtableschema['colnames'] as $col){
$table->text($col);
}
etc.
});
The error I get is that the variables is not defined. I don't know how to give the user's input to the schema::create method.
I can't find any method in the documentation for creating tables in this way, or anything similar to this during my last 3 hours of googling. The eloquent syntax confuses me sometimes so maybe I'm missing something obvious.
Any ideas? Or is there an alternative pure php/sql to accomplish this?
Many thanks
edit: my apologies, I made a typo earlier in my example code. My issue is that I don't know how to pass the variables I want to schema::create()
Upvotes: 3
Views: 4312
Reputation: 146219
You may use use($newtableschema)
to pass the variable into the closure
:
Schema::create($newtableschema['tablename'], function($table) use($newtableschema) {
// So now you can access the $newtableschema variable here
// Rest of your code...
});
Upvotes: 7
Reputation: 111869
If you put $variable into single quotes PHP think it's normal text so the string is displayed as it was written. You should look at this code:
$colname = 'something';
echo '$colname'.'<br />';
echo "$colname".'<br />';
echo "{$colname}".'<br />';
echo $colname.'<br />';
Output for this will be:
$colname
something
something
something
So it's obviously not Eloquent related.
You used:
$table->text('$colname');
so you tried to create Text file with name exact $colname
if you want to use it as variable you should simple use in this case:
$table->text($colname);
Upvotes: 0
Reputation: 939
First of all... '$colname' is not the same thing as "$colname" and it should be just $colname with no apostrophes.
I am not sure if that will work... but you can try my way.
$table->text('$colname'); $table->text($colname);
Upvotes: 1