Home » Php » Laravel 5 How to configure the Queue database driver to connect to a non-default database?

Laravel 5 How to configure the Queue database driver to connect to a non-default database?

Posted by: admin November 29, 2017 Leave a comment

Questions:

In Laravel 5.1, we can set the Queue connection configurations in config/queue.php.

QUEUE_DRIVER=database

    'database' => [
        'driver' => 'database',
        'table' => 'jobs',
        'queue' => 'default',
        'expire' => 60,
    ],

However, it will only use the default database connection in config/database.php.

If I have 2 database, 1 default database mysql1 in localhost, and 1 database mysql2 in a remote server, and the Queue jobs table is in the remote database mysql2, how can I configure the Queue database driver to use the remote mysql2 database? Please note that the main App is using the default database in localhost.

Answers:

You can use the 'connection' parameter in queue.php to set the correct database connection ( from the ones you’ve defined in database.php ).

'database' => [
'connection' => 'mysql2'
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],

I was looking for the same thing and found it in the source code.

NOTE: This will not only read the jobs from this connection ( when running the queue ), but also write them to this connection ( when dispatching a new Job ) .

Questions:
Answers:

The best answer here did not work for me, not to say it isn’t the best answer for a different issue than mine. My issue was that Laravel did not cache my config settings.

After going into file \config\queue.php and changing the default driver…

'default' => env('QUEUE_DRIVER', 'database'),

The queue was still running on the sync driver.

I then checked the file…

    \bootstrap\cache\config.php

Around line 30 I saw this…

 'queue' => 
array (
'default' => 'sync', 

…but to connect to the database, it should be…

 'queue' => 
array (
'default' => 'database',

This resolved the issue…

php artisan config:cache

Running the config:cache commmand rewrites the config.php file to the current driver settings.

Questions:
Answers:

You can set the $connection variable in the model. Note that this will only affect Eloquent queries and will not work for the Fluid Query Builder.

class Jobs extends Eloquent {
    protected $connection = "database2"     
}

This would of course require you to have a 2nd named connection in your config/database.php file that is 'database2' => [...].