What Is The Best Way To Run A Laravel Scheduled Task Over Multiple Databases?
I have a laravel web app where each client has its own database. All the database connections are defined as connections in config/database.php. I connect to appropriate database according to the subdomain the request is coming from. Now there is some cleaning task that I need to run every midnight. I have created a command to achieve the task and it works for the default database the laravel app is currently configured to in .env file. Hoewever, what is the best way to iterate this task for all client databases?
Answer
It's very easy to accomplish with Laravel's Config
class. I had the same problem of connecting with multiple MySQL servers and multiple databases to get some information from the server. And I had to deal with an un-defined number of servers. So I found a universal solution that will work for you too!
Consider this structure for your command's Handle() function:
public function handle()
{
$arrayOfConnections = config('database.connections'); // Array of connections
foreach($arrayOfConnections as $connection){
// Setting Config
Config::set('database.connections.dynamicConnection.host',$connection->host);
Config::set('database.connections.dynamicConnection.password',$connection->connection);
// More of your config
// Your Logic Here
// Purge the configuration (It is important!)
DB::purge('dynamicConnection');
}
}
Of course, you have to exclude dynamicConnection
from the array which will require one ternary operator or one condition. But this is how I did it. Mine is not exactly the same, I get the values from the database as it's not good to update config file every few minutes and it's not good to have information about hundreds of servers in the config file. But this will work for you (Consider this code as logic, not magic that will work out of the box for your specific situation without edits)
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?