{"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<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Step_1_Connect_Multiple_Databases_in_Laravel_11\" >Step 1: Connect Multiple Databases in Laravel 11<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Set_env_Variables\" >Set .env Variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Configure_Database_Connections\" >Configure Database Connections<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Creating_Migrations_for_Multiple_Databases\" >Creating Migrations for Multiple Databases<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Using_Multiple_Database_Connections_in_Models\" >Using Multiple Database Connections in Models<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Using_Multiple_Database_Connections_in_Controllers\" >Using Multiple Database Connections in Controllers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#Getting_Data_from_Multiple_Databases_Using_DB_Facade\" >Getting Data from Multiple Databases Using DB Facade<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/debugspot.com\/blogs\/how-to-connect-multiple-database-in-laravel-11\/#You_may_also_find_interesting\" >You may also find interesting:<\/a><\/li><\/ul><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_1_Connect_Multiple_Databases_in_Laravel_11\"><\/span>Step 1: Connect Multiple Databases in Laravel 11<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<h5><span class=\"ez-toc-section\" id=\"Set_env_Variables\"><\/span>Set .env Variables<span class=\"ez-toc-section-end\"><\/span><\/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><span class=\"ez-toc-section\" id=\"Configure_Database_Connections\"><\/span>Configure Database Connections<span class=\"ez-toc-section-end\"><\/span><\/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><span class=\"ez-toc-section\" id=\"Creating_Migrations_for_Multiple_Databases\"><\/span>Creating Migrations for Multiple Databases<span class=\"ez-toc-section-end\"><\/span><\/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><span class=\"ez-toc-section\" id=\"Using_Multiple_Database_Connections_in_Models\"><\/span>Using Multiple Database Connections in Models<span class=\"ez-toc-section-end\"><\/span><\/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><span class=\"ez-toc-section\" id=\"Using_Multiple_Database_Connections_in_Controllers\"><\/span>Using Multiple Database Connections in Controllers<span class=\"ez-toc-section-end\"><\/span><\/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><span class=\"ez-toc-section\" id=\"Getting_Data_from_Multiple_Databases_Using_DB_Facade\"><\/span>Getting Data from Multiple Databases Using DB Facade<span class=\"ez-toc-section-end\"><\/span><\/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><span class=\"ez-toc-section\" id=\"You_may_also_find_interesting\"><\/span>You may also find interesting:<span class=\"ez-toc-section-end\"><\/span><\/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}]}}