Laravel / Model / Multiple Database Connections
Multiple Database Connections
-
STEPS
1. Set ENV Variable:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=mydatabase DB_USERNAME=root DB_PASSWORD=root DB_CONNECTION_SECOND=mysql DB_HOST_SECOND=127.0.0.1 DB_PORT_SECOND=3306 DB_DATABASE_SECOND=mydatabase2 DB_USERNAME_SECOND=root DB_PASSWORD_SECOND=root 2. Database Configuration:
config/database.php
use Illuminate\Support\Str; return [ 'default' => env('DB_CONNECTION', 'mysql'), 'connections' => [ ..... 'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), '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' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], 'mysql_second' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL_SECOND'), 'host' => env('DB_HOST_SECOND', '127.0.0.1'), 'port' => env('DB_PORT_SECOND', '3306'), 'database' => env('DB_DATABASE_SECOND', 'forge'), 'username' => env('DB_USERNAME_SECOND', 'forge'), 'password' => env('DB_PASSWORD_SECOND', ''), 'unix_socket' => env('DB_SOCKET_SECOND', ''), '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'), ]) : [], ], 3. Getting Data from Multiple Database using DB:
1. routes/web.php
2. Multiple Database Connections with Model:Route::get('/get-mysql-blogs', function () { $products = DB::table("blogs")->get(); dd($products); }); Route::get('/get-mysql-second-blogs', function () { $products = DB::connection('mysql_second')->table("blogs")->get(); dd($products); });
3. Multiple Database Connections in Controller:namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Blog extends Model { use HasFactory; protected $connection = 'mysql_second'; protected $fillable = [ 'id', 'title', 'body' ]; } namespace App\Http\Controllers; use App\Models\Blog; class BlogController extends Controller { /** * Write code on Method * * @return response() */ public function getRecord() { $blog = new Blog; $blog->setConnection('mysql_second'); $something = $blog->find(1); return $something; } }