48
loading...
This website collects cookies to deliver better user experience
config/database.php
:'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => 'database1',
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
ModelName::connection($databaseName)
.config/database.php
if you have for example more than 100 clients. And it is kind of tedious to repeat every time you have a new client.config/database.php
but this won't make your file less big.Artisan
command.Artisan
command will store the client in the main database (which is the only database defined on config/database.php
), create the client database and finally migrate all migrations. All of that using only one simple artisan
command line. Something like php artisan client:make Client1
. The name of the database will be Client1
in this case.ModelName::connection($clientDatabaseName)
, you create a Trait where you will define the following:$clientDatabaseName = MainDatabase::where('client_name', $request->client_name)->value('database_name');
config(['database.connections.mysql.database' => $clientDatabaseName]);
\DB::purge('mysql');
\DB::reconnect('mysql');
AppServiceProvider
.config/database.php
and you won't have to use connection($db)
every time you need to instantiate a Model
. Only with a simple artisan
command line, you take care of creating the database and its migrations and seeders if you have any.