0

My requirement is pretty simple and I found a lot of solutions, but none of them is working for me.

I have two MySQL databases, one where all write operations will happen and there is a replica of this database, which is read-only. I am creating a middleware where if a request is GET, it should use read-only database otherwise main databases.

I already have tried these:

DB::disconnect();
Config::set('database.default', 'mysql_readonly');
DB::reconnect('mysql_readonly');


Config::set('database.default', 'mysql_readonly');
DB::purge('mysql_readonly');


DB::disconnect();
Config::set('database.default', 'mysql_readonly');
DB::connection('mysql_readonly');

None of the solutions is working.

  • Laravel Version: 8.59.0
  • PHP Version: 8.0.10
2
  • Instead of "right operations" you mean "write operations"? Commented Oct 22, 2021 at 18:52
  • Yes, typo error. @JamesZ Commented Oct 23, 2021 at 5:53

1 Answer 1

1

I found the working solution.

$readOnlyConfig = config('database.connections.mysql_readonly');
Config::set('database.connections.mysql', $readOnlyConfig);
DB::purge();
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that'll do it. I really wish they'd picked a different function name than purge, because it's a little terrifying the first couple times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.