2

I use DB::setDatabaseName(<database name>) to reset the databasename, then I use DB::table(<table name>)->get() to retrieve data. However laravel does not change to new database.

This is my error message:

Illuminate/Database/QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "t" does not exist LINE 1: select * from "t" ^ (SQL: select * from "t")'

The table t is in another database. I think when I use DB::setDatabaseName(<database name>) it would work.

Thank you for your help!

hello
  • 1,168
  • 4
  • 24
  • 59
ray
  • 241
  • 2
  • 13

2 Answers2

0

I don't know your database of detail information, but this help you to check database have changed.

// current database is 'db_1'
echo DB::getDatabaseName(); // return db_1

// Set database to 'db_2'
DB::setDatabaseName('db_2');

// If success, should return 'db_2' now.
echo DB::getDatabaseName();

// Check database tables.
DB::select('show tables');
Calos
  • 1,783
  • 19
  • 28
  • I use the postgresql, when I use DB::select("SELECT * FROM pg_catalog.pg_tables where tableowner = ''") to check the result. The result that display previous tables. Is it the bug of framework? – ray Dec 25 '18 at 06:26
  • What you mean is that calling `DB::getDatabaseName()` will see that the database has changed, and will it get the same results as the previous database when running SQL? – Calos Dec 25 '18 at 08:22
0

I was facing a similar issue.
But changing the database solely might not always work.

You could use config->set() like so

config()->set('database.connections.mysql', $database_name);

But in my case I had to reconnect the database to change it dynamically.
So maybe this one works for the OP.

\DB::disconnect(); 
config()->set('database.pgsql.database', $database_name); // psgl = Postgress
\DB::reconnect();

You'll find more info here Laravel 6 config()->get('database.connections.mysql') not matching DB:connection()

Hope it helps

leopold
  • 1,971
  • 1
  • 19
  • 22