3

How can a database connection be changed when user is admin role? Admin database contains information that must not be accessible to other user's and requirement also is that database must be located on own server. I do have currently separate configuration for admin connection.

'mysql' => [
    'host'      => 'admin.psa44.localhost'
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'secretpassword',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
],

I want that no hardcoding is in application so how can Laravel do the switch when necessary? Thanks for any help.

1 Answers1

4

You need to create new database config rule in appconfig.

'mysql' => [
    'host'      => 'admin.psa44.localhost'
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'secretpassword',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
],
'mysql_admin' => [
    'host'      => 'admin.psa44.localhost'
    'driver'    => 'mysql',
    'database'  => 'admindatabase',
    'username'  => 'root',
    'password'  => 'secretpassword1',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
],

I named mysql_admin. In migration when use

Schema::create('some_table', function($table)

to create table ,use

Schema::connection('mysql_admin')->create('some_table', function($table)

to create that table in other database.

For query to that database do something like this

$admins = DB::connection('mysql_admin')->select(...);

And you can to define connection for model

class AdminModel extends Eloquent {

    protected $connection = 'mysql_admin';

}
amin saffar
  • 1,953
  • 3
  • 22
  • 34