What Is The Best Way To Run A Laravel Scheduled Task Over Multiple Databases?

- 1 answer

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?



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
        // More of your config

        // Your Logic Here

        // Purge the configuration (It is important!)


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)