PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 30, 2022

[FIXED] How to change database name before authentication in laravel 5.1

 January 30, 2022     laravel, laravel-5.1, php     No comments   

Issue

I have multiple database. I want to change db name based on the url dynamically. How can I set particular db before authentication.

I want to change database from authentication to through out the application. For ex. If url is like lara.local.com/comapny1 then it will select database company1

If url is like lara.local.com/company2 then it will select database company2

Based on the selected database authentication will be done and selected database will be used for that user.


Solution

Make entry for second database in config/database.php

'company1' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'database1'),
    'username'  => env('DB_USERNAME', 'root'),
    'password'  => env('DB_PASSWORD', ''),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
    ],

    'company2' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => 'database2',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
     ],

By default your queries will use the mysql connection to change connection to 'company1'

DB::connection('company1')->select($query);

Additionally you can set database connection for Model

$someModel = new MyModel;
$someModel->setConnection('company1');

You can use the Request::is() to get URI from URL

if(Request::is('company1')){
    //change database to company1
    Config::set("database.connections.company1.database", 'company1');
}
elseif(Request::is('company2'){
    Config::set("database.connections.company1.database", 'company2');
}


Answered By - Saad
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing