I am trying to dynamically create database for different users. (every user will have their own database server, so don't ask why I am not using a single database for all users) To do that, I have a default database storing all the connection information. I will need to:
Is there a way I can dynamically set the database connection of the migration file based on the information I have on the default database?
P.S. For "dynamically set the database connection", I am NOT meaning the normal setting as you do in controller or class. I expect something that would at least create migration table in the target database and be able to self-detect what migration file to run.
Laravel Migration is an essential feature in Laravel that allows you to create a table in your database. It allows you to modify and share the application's database schema. You can modify the table by adding a new column or deleting an existing column.
Migrations are optional but recommended. @ecksdee if you don't add a migration which creates a table in the database then you don't need Model in Laravel terms at all, because an Eloquent model is just an object relational mapper to a table that is part of your database.
Navigate to your project folder and run the following commands to create new: Model: php artisan make:model YourModelName. Controller: php artisan make:controller YourControllerName. Migration: php artisan make:migration create_users_table.
Yes there is. First you need to add the connection details to the configuration. Once you have a named connection configured, just call the migrate
command on the Artisan facade, selecting the name of the connection ("new" in this example) as option:
use Illuminate\Support\Facades\Artisan;
//...
$new_connection = 'new';
config(["database.connections.$new_connection" => [
// fill with dynamic data:
"driver" => "mysql",
"host" => "",
"port" => "",
"database" => "",
"username" => "",
"password" => "",
"charset" => "utf8",
"collation" => "utf8_unicode_ci",
"prefix" => "",
"strict" => true,
"engine" => null
]]);
Artisan::call('migrate', ['--database' => $new_connection]);
First you need to create the database
DB::getConnection()->statement('CREATE DATABASE :schema', array('schema' => $schemaName));
Then change the name of the database on the fly like this
$config = app(\Illuminate\Config\Repository::class);
$config->set('database.connections.mysql.database', UserRepotory::getCurrentDatabase());
You can include Config
like this or trough laravel's service container.
And finally you call Artisan::call('migrate')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With