Dynamic Database Connection Using Laravel












0















I am working on a new application that must connect to several databases. The databases are dynamically created when a new company is registered in my application i.e each company have there on databases.



My question is how to establish the database connection using laravel,



If the company admin is login he needs to connect the corresponding db. How is it possible ???



I know how to establish multiple database connection if the databases are stable, like,



'mysql1' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge1'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...

'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge2'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...


but if the databases are not stable how is it possible ????



If my question is not up to standard, please forgive me










share|improve this question





























    0















    I am working on a new application that must connect to several databases. The databases are dynamically created when a new company is registered in my application i.e each company have there on databases.



    My question is how to establish the database connection using laravel,



    If the company admin is login he needs to connect the corresponding db. How is it possible ???



    I know how to establish multiple database connection if the databases are stable, like,



    'mysql1' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge1'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    ...

    'mysql2' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge2'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    ...


    but if the databases are not stable how is it possible ????



    If my question is not up to standard, please forgive me










    share|improve this question



























      0












      0








      0








      I am working on a new application that must connect to several databases. The databases are dynamically created when a new company is registered in my application i.e each company have there on databases.



      My question is how to establish the database connection using laravel,



      If the company admin is login he needs to connect the corresponding db. How is it possible ???



      I know how to establish multiple database connection if the databases are stable, like,



      'mysql1' => [
      'driver' => 'mysql',
      'host' => env('DB_HOST', '127.0.0.1'),
      'port' => env('DB_PORT', '3306'),
      'database' => env('DB_DATABASE', 'forge1'),
      'username' => env('DB_USERNAME', 'forge'),
      'password' => env('DB_PASSWORD', ''),
      ...

      'mysql2' => [
      'driver' => 'mysql',
      'host' => env('DB_HOST', '127.0.0.1'),
      'port' => env('DB_PORT', '3306'),
      'database' => env('DB_DATABASE', 'forge2'),
      'username' => env('DB_USERNAME', 'forge'),
      'password' => env('DB_PASSWORD', ''),
      ...


      but if the databases are not stable how is it possible ????



      If my question is not up to standard, please forgive me










      share|improve this question
















      I am working on a new application that must connect to several databases. The databases are dynamically created when a new company is registered in my application i.e each company have there on databases.



      My question is how to establish the database connection using laravel,



      If the company admin is login he needs to connect the corresponding db. How is it possible ???



      I know how to establish multiple database connection if the databases are stable, like,



      'mysql1' => [
      'driver' => 'mysql',
      'host' => env('DB_HOST', '127.0.0.1'),
      'port' => env('DB_PORT', '3306'),
      'database' => env('DB_DATABASE', 'forge1'),
      'username' => env('DB_USERNAME', 'forge'),
      'password' => env('DB_PASSWORD', ''),
      ...

      'mysql2' => [
      'driver' => 'mysql',
      'host' => env('DB_HOST', '127.0.0.1'),
      'port' => env('DB_PORT', '3306'),
      'database' => env('DB_DATABASE', 'forge2'),
      'username' => env('DB_USERNAME', 'forge'),
      'password' => env('DB_PASSWORD', ''),
      ...


      but if the databases are not stable how is it possible ????



      If my question is not up to standard, please forgive me







      laravel database-connection






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 10:33







      JIJOMON K.A

















      asked Nov 16 '18 at 9:58









      JIJOMON K.AJIJOMON K.A

      1,096624




      1,096624
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You can add dynamically the database configuration like this.



          if(NULL === config()->get('database.connections.company')){
          config()->set('database.connections.company', [
          'driver' => $companyDbDriver,
          'host' => $companyDbHost,
          'port' => $companyDbPort,
          'database' => $companyDbName,
          'username' => $companyDbUser,
          'password' => $companyDbPassword,
          'charset' => 'utf8',
          'collation' => 'utf8_unicode_ci',
          'prefix' => '',
          'strict' => false
          ]);
          }


          in the model; set the connection attribute to 'company'



          /**
          * Connection configuration ID.
          *
          * @var string
          */
          protected $connection = 'company';


          there are complication if you dont load the configuration of the database before calling the models using it, i'll leave that to you.






          share|improve this answer































            0














            First you have to know where your database connections parameters are stored.
            Anyway, wherever they are, you should create a new connection on the fly.
            Supposing each User has it's own connection ...



            <?php
            use IlluminateSupportFacadesConfig;

            $user = Users::find($id);
            Config::set('database.connections.' . $user->username, array(
            'driver' => 'mysql',
            'host' => $user->db_host,
            'database' => $user->db_name,
            'username' => $user->db_user,
            'password' => $user->db_pass,
            'charset' => 'utf8',
            'collation' => 'utf8_general_ci',
            'prefix' => '',
            ));
            // And set the new connection to interested models
            $myModel = new MyModel;
            $myModel->setConnection($user->username);
            $data = $myModel->where(...)->get();


            Hope this help






            share|improve this answer
























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335397%2fdynamic-database-connection-using-laravel%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              You can add dynamically the database configuration like this.



              if(NULL === config()->get('database.connections.company')){
              config()->set('database.connections.company', [
              'driver' => $companyDbDriver,
              'host' => $companyDbHost,
              'port' => $companyDbPort,
              'database' => $companyDbName,
              'username' => $companyDbUser,
              'password' => $companyDbPassword,
              'charset' => 'utf8',
              'collation' => 'utf8_unicode_ci',
              'prefix' => '',
              'strict' => false
              ]);
              }


              in the model; set the connection attribute to 'company'



              /**
              * Connection configuration ID.
              *
              * @var string
              */
              protected $connection = 'company';


              there are complication if you dont load the configuration of the database before calling the models using it, i'll leave that to you.






              share|improve this answer




























                0














                You can add dynamically the database configuration like this.



                if(NULL === config()->get('database.connections.company')){
                config()->set('database.connections.company', [
                'driver' => $companyDbDriver,
                'host' => $companyDbHost,
                'port' => $companyDbPort,
                'database' => $companyDbName,
                'username' => $companyDbUser,
                'password' => $companyDbPassword,
                'charset' => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix' => '',
                'strict' => false
                ]);
                }


                in the model; set the connection attribute to 'company'



                /**
                * Connection configuration ID.
                *
                * @var string
                */
                protected $connection = 'company';


                there are complication if you dont load the configuration of the database before calling the models using it, i'll leave that to you.






                share|improve this answer


























                  0












                  0








                  0







                  You can add dynamically the database configuration like this.



                  if(NULL === config()->get('database.connections.company')){
                  config()->set('database.connections.company', [
                  'driver' => $companyDbDriver,
                  'host' => $companyDbHost,
                  'port' => $companyDbPort,
                  'database' => $companyDbName,
                  'username' => $companyDbUser,
                  'password' => $companyDbPassword,
                  'charset' => 'utf8',
                  'collation' => 'utf8_unicode_ci',
                  'prefix' => '',
                  'strict' => false
                  ]);
                  }


                  in the model; set the connection attribute to 'company'



                  /**
                  * Connection configuration ID.
                  *
                  * @var string
                  */
                  protected $connection = 'company';


                  there are complication if you dont load the configuration of the database before calling the models using it, i'll leave that to you.






                  share|improve this answer













                  You can add dynamically the database configuration like this.



                  if(NULL === config()->get('database.connections.company')){
                  config()->set('database.connections.company', [
                  'driver' => $companyDbDriver,
                  'host' => $companyDbHost,
                  'port' => $companyDbPort,
                  'database' => $companyDbName,
                  'username' => $companyDbUser,
                  'password' => $companyDbPassword,
                  'charset' => 'utf8',
                  'collation' => 'utf8_unicode_ci',
                  'prefix' => '',
                  'strict' => false
                  ]);
                  }


                  in the model; set the connection attribute to 'company'



                  /**
                  * Connection configuration ID.
                  *
                  * @var string
                  */
                  protected $connection = 'company';


                  there are complication if you dont load the configuration of the database before calling the models using it, i'll leave that to you.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 16 '18 at 10:28









                  N69SN69S

                  1,170515




                  1,170515

























                      0














                      First you have to know where your database connections parameters are stored.
                      Anyway, wherever they are, you should create a new connection on the fly.
                      Supposing each User has it's own connection ...



                      <?php
                      use IlluminateSupportFacadesConfig;

                      $user = Users::find($id);
                      Config::set('database.connections.' . $user->username, array(
                      'driver' => 'mysql',
                      'host' => $user->db_host,
                      'database' => $user->db_name,
                      'username' => $user->db_user,
                      'password' => $user->db_pass,
                      'charset' => 'utf8',
                      'collation' => 'utf8_general_ci',
                      'prefix' => '',
                      ));
                      // And set the new connection to interested models
                      $myModel = new MyModel;
                      $myModel->setConnection($user->username);
                      $data = $myModel->where(...)->get();


                      Hope this help






                      share|improve this answer




























                        0














                        First you have to know where your database connections parameters are stored.
                        Anyway, wherever they are, you should create a new connection on the fly.
                        Supposing each User has it's own connection ...



                        <?php
                        use IlluminateSupportFacadesConfig;

                        $user = Users::find($id);
                        Config::set('database.connections.' . $user->username, array(
                        'driver' => 'mysql',
                        'host' => $user->db_host,
                        'database' => $user->db_name,
                        'username' => $user->db_user,
                        'password' => $user->db_pass,
                        'charset' => 'utf8',
                        'collation' => 'utf8_general_ci',
                        'prefix' => '',
                        ));
                        // And set the new connection to interested models
                        $myModel = new MyModel;
                        $myModel->setConnection($user->username);
                        $data = $myModel->where(...)->get();


                        Hope this help






                        share|improve this answer


























                          0












                          0








                          0







                          First you have to know where your database connections parameters are stored.
                          Anyway, wherever they are, you should create a new connection on the fly.
                          Supposing each User has it's own connection ...



                          <?php
                          use IlluminateSupportFacadesConfig;

                          $user = Users::find($id);
                          Config::set('database.connections.' . $user->username, array(
                          'driver' => 'mysql',
                          'host' => $user->db_host,
                          'database' => $user->db_name,
                          'username' => $user->db_user,
                          'password' => $user->db_pass,
                          'charset' => 'utf8',
                          'collation' => 'utf8_general_ci',
                          'prefix' => '',
                          ));
                          // And set the new connection to interested models
                          $myModel = new MyModel;
                          $myModel->setConnection($user->username);
                          $data = $myModel->where(...)->get();


                          Hope this help






                          share|improve this answer













                          First you have to know where your database connections parameters are stored.
                          Anyway, wherever they are, you should create a new connection on the fly.
                          Supposing each User has it's own connection ...



                          <?php
                          use IlluminateSupportFacadesConfig;

                          $user = Users::find($id);
                          Config::set('database.connections.' . $user->username, array(
                          'driver' => 'mysql',
                          'host' => $user->db_host,
                          'database' => $user->db_name,
                          'username' => $user->db_user,
                          'password' => $user->db_pass,
                          'charset' => 'utf8',
                          'collation' => 'utf8_general_ci',
                          'prefix' => '',
                          ));
                          // And set the new connection to interested models
                          $myModel = new MyModel;
                          $myModel->setConnection($user->username);
                          $data = $myModel->where(...)->get();


                          Hope this help







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 16 '18 at 10:33









                          simonecoscisimonecosci

                          82659




                          82659






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335397%2fdynamic-database-connection-using-laravel%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Xamarin.iOS Cant Deploy on Iphone

                              Glorious Revolution

                              Dulmage-Mendelsohn matrix decomposition in Python