{"id":1589,"date":"2024-09-12T07:10:37","date_gmt":"2024-09-12T07:10:37","guid":{"rendered":"https:\/\/debugspot.com\/?p=1589"},"modified":"2024-10-23T04:45:34","modified_gmt":"2024-10-23T04:45:34","slug":"how-to-connect-multiple-database-in-laravel-11","status":"publish","type":"post","link":"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/","title":{"rendered":"How to Connect Multiple Database in Laravel 11: A Comprehensive Guide"},"content":{"rendered":"<p>In this article, we&#8217;ll show you how to connect multiple databases in Laravel 11. We&#8217;ll cover how to set up connections for MySQL, MongoDB, and PostgreSQL, and provide examples for creating migrations, models, and queries.<\/p>\n<p>Laravel is a popular PHP framework that makes web development easier with its elegant features. One of these features is the ability to connect to multiple databases. This can be useful when you need to handle different types of data, such as user data, product data, or analytics data. In this guide, we&#8217;ll walk you through the steps to set up multiple database connections in Laravel, with practical examples.<\/p>\n<p>The configuration for Laravel&#8217;s database connections is found in the <code>config\/database.php<\/code> file. In this file, you can define your database connections and specify which one should be used by default.<\/p>\n<h3 class=\"wp-block-heading\">Step 1: Connect Multiple Databases in Laravel 11<\/h3>\n<h5>Set .env Variables<\/h5>\n<p>First, add the database configurations to your <code>.env<\/code> file as shown below:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\n\/\/ Database 1\r\nDB_CONNECTION=mysql\r\nDB_HOST=127.0.0.1\r\nDB_PORT=3306\r\nDB_DATABASE=database_1\r\nDB_USERNAME=root\r\nDB_PASSWORD=\r\n\r\n\/\/ Database 2\r\nDB_CONNECTION_SECOND=mysql\r\nDB_HOST_SECOND=127.0.0.1\r\nDB_PORT_SECOND=3306\r\nDB_DATABASE_SECOND=database_2\r\nDB_USERNAME_SECOND=root\r\nDB_PASSWORD_SECOND=\r\n<\/code><\/pre>\n<h5>Configure Database Connections<\/h5>\n<p>Next, open the <code>config\/database.php<\/code> file and add a new connection key like this:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nuse Illuminate\\Support\\Str;\r\n\r\nreturn [\r\n\r\n    'default' => env('DB_CONNECTION', 'mysql'),   \r\n\r\n    'connections' => [\r\n\r\n        \/\/ Default MySQL connection\r\n        'mysql' => [\r\n            'driver' => 'mysql',\r\n            'url' => env('DATABASE_URL'),\r\n            'host' => env('DB_HOST', '127.0.0.1'),\r\n            'port' => env('DB_PORT', '3306'),\r\n            'database' => env('DB_DATABASE', 'forge'),\r\n            'username' => env('DB_USERNAME', 'root'),\r\n            'password' => env('DB_PASSWORD', ''),\r\n            'unix_socket' => env('DB_SOCKET', ''),\r\n            'charset' => 'utf8mb4',\r\n            'collation' => 'utf8mb4_unicode_ci',\r\n            'prefix' => '',\r\n            'prefix_indexes' => true,\r\n            'strict' => true,\r\n            'engine' => null,\r\n            'options' => extension_loaded('pdo_mysql') ? array_filter([\r\n                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),\r\n            ]) : [],\r\n        ],\r\n\r\n        \/\/ Second MySQL connection\r\n        'mysql2' => [\r\n            'driver' => env('DB_CONNECTION_SECOND'),\r\n            'host' => env('DB_HOST_SECOND', '127.0.0.1'),\r\n            'port' => env('DB_PORT_SECOND', '3306'),\r\n            'database' => env('DB_DATABASE_SECOND', 'forge'),\r\n            'username' => env('DB_USERNAME_SECOND', 'root'),\r\n            'password' => env('DB_PASSWORD_SECOND', ''),\r\n            'unix_socket' => '',\r\n            'charset' => 'utf8mb4',\r\n            'collation' => 'utf8mb4_unicode_ci',\r\n            'prefix' => '',\r\n            'prefix_indexes' => true,\r\n            'strict' => true,\r\n            'engine' => null,\r\n        ],\r\n\r\n    ],\r\n<\/code><\/pre>\n<h5>Creating Migrations for Multiple Databases<\/h5>\n<p>Now, let&#8217;s create migrations for each database:<\/p>\n<p>Default Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\npublic function up(): void\r\n{\r\n    Schema::create('users', function (Blueprint $table) {\r\n        $table->increments('id');\r\n        $table->string('name');\r\n        $table->string('email');\r\n        $table->timestamps();\r\n    });\r\n}\r\n<\/code><\/pre>\n<p>Second Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\npublic function up(): void\r\n{\r\n    Schema::connection('mysql2')->create('users', function (Blueprint $table) {\r\n        $table->increments('id');\r\n        $table->string('name');\r\n        $table->string('email');\r\n        $table->timestamps();\r\n    });\r\n}\r\n<\/code><\/pre>\n<h5>Using Multiple Database Connections in Models<\/h5>\n<p>Here&#8217;s how to specify which connection a model should use:<\/p>\n<p>Default Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nnamespace App\\Models;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass User extends Model\r\n{\r\n    use HasFactory;\r\n\r\n    protected $fillable = [\r\n        'name', 'email'\r\n    ];\r\n}\r\n<\/code><\/pre>\n<p>Second Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nnamespace App\\Models;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass User extends Model\r\n{\r\n    use HasFactory;\r\n\r\n    protected $connection = 'mysql2';\r\n\r\n    protected $fillable = [\r\n        'name', 'email'\r\n    ];\r\n}\r\n<\/code><\/pre>\n<h5>Using Multiple Database Connections in Controllers<\/h5>\n<p>Here&#8217;s how to access different databases in a controller:<\/p>\n<p>Default Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nclass UsersController extends BaseController\r\n{\r\n    public function getRecord()\r\n    {\r\n        $users = Users::get();\r\n        return $find;\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Second Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nclass UsersController extends BaseController\r\n{\r\n    public function getRecord()\r\n    {\r\n        $users = new Users;\r\n        $users->setConnection('mysql2');\r\n        $find = $users->find(1);\r\n        return $find;\r\n    }\r\n}\r\n<\/code><\/pre>\n<h5>Getting Data from Multiple Databases Using DB Facade<\/h5>\n<p>Here\u2019s how to get data from each database:<\/p>\n<p>Default Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\n$users = DB::table(\"users\")->get();\r\nprint_r($users);\r\n<\/code><\/pre>\n<p>Second Database:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\n$users = DB::connection('mysql2')->table(\"users\")->get();\r\nprint_r($users);\r\n<\/code><\/pre>\n<p>For more details, you can check the <a href=\"https:\/\/laravel.com\/docs\/11.x\/database\" target=\"_blank\" rel=\"noopener\">Laravel Documentation<\/a><\/p>\n<h5>You may also find interesting:<\/h5>\n<p><a href=\"https:\/\/debugspot.com\/blogs\/how-to-avoid-tokenmismatch-error-laravel\/\" target=\"_blank\" title=\"How to avoid TokenMismatchException on logout\" rel=\"noopener\">How to avoid TokenMismatchException on logout<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;ll show you how to connect multiple databases in Laravel 11. We&#8217;ll cover how to set up connections for MySQL, MongoDB, and PostgreSQL, and provide examples for creating migrations, models, and queries. Laravel is a popular PHP framework that makes web development easier with its elegant features. One of these features is the ability to connect to multiple databases. This can be useful when you need to handle different types of data, such as user data, product data, or analytics data. In this guide, we&#8217;ll walk you through the steps to set up multiple database connections in Laravel, with practical examples. The configuration for Laravel&#8217;s database connections is found in the config\/database.php file. In this file, you can define your database connections and specify which one should be used by default. Step 1: Connect Multiple Databases in Laravel 11 Set .env Variables First, add the database configurations to your .env file as shown below: \/\/ Database 1 DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database_1 DB_USERNAME=root DB_PASSWORD= \/\/ Database 2 DB_CONNECTION_SECOND=mysql DB_HOST_SECOND=127.0.0.1 DB_PORT_SECOND=3306 DB_DATABASE_SECOND=database_2 DB_USERNAME_SECOND=root DB_PASSWORD_SECOND= Configure Database Connections Next, open the config\/database.php file and add a new connection key like this: use Illuminate\\Support\\Str; return [ &#8216;default&#8217; => env(&#8216;DB_CONNECTION&#8217;, &#8216;mysql&#8217;), &#8216;connections&#8217; &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"rank_math_lock_modified_date":false,"footnotes":""},"categories":[3],"tags":[32,30,31,33,34],"class_list":["post-1589","post","type-post","status-publish","format-standard","hentry","category-laravel","tag-custom-middleware","tag-laravel-11","tag-laravel-middleware","tag-middleware-configuration","tag-middleware-in-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1589"}],"collection":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/comments?post=1589"}],"version-history":[{"count":6,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1589\/revisions"}],"predecessor-version":[{"id":1595,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1589\/revisions\/1595"}],"wp:attachment":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/media?parent=1589"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/categories?post=1589"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/tags?post=1589"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}