Step 1
Go to config/database.php and update like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
'mysql_2' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], |
Step 2
Then make connection in any controller like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
namespace App\Http\Controllers; use Illuminate\Http\Request; use PDO; use PDOException; use DB; use Config; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class YourController extends Controller { public function CreateDB() { $database = 'database_name'; try { $pdo = $this->getPDOConnection(env('DB_HOST'), env('DB_PORT'), env('DB_USERNAME'), env('DB_PASSWORD')); $created = $pdo->exec(sprintf( 'CREATE DATABASE IF NOT EXISTS %s', $database )); if($created){ echo sprintf('Successfully created %s database', $database); }else{ echo sprintf('Failed to create %s database', $database); } } catch (PDOException $exception) { echo sprintf('Failed to create %s database, %s', $database, $exception->getMessage()); } } public function GetConnection($db_name) { Config::set('database.connections.mysql_2.database', $db_name); return DB::connection('mysql_2'); } public function Migration($db_name) { Schema::connection($db_name)->create('tests', function (Blueprint $table) { $table->increments('id'); $table->string('data'); $table->timestamps(); }); return true; } } |
Leave a reply