I've been tasked with making our Laravel code connect to a different database as the main database when the url is different. Our website is accessible by 2 urls:
a.mycompany.com
and b.mycompany.com
I know the main database connection details are configured in config/database.php
, but I've read that it's very much discouraged to try to conditionally change config variables there. Nonetheless, if I wanted to, could I check for the current url and change the connection details in that file? How would I do that?
For these purposes, you need to configure the necessary connections in config/database.php. For example, for MySQL, add two connections:
Then directly in the code, use the desired connection:
To determine which domain it is, you can use suddomain routing:
Then use $domain to check which site it is and use the correct connection.
It is also possible to establish a model-specific connection using the $connection property: