Laravel 5 How to configure the Queue database driver to connect to a non-default database?
Solution 1
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 ) .
Solution 2
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.
Solution 3
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' => [...]
.
userpal
Updated on June 13, 2022Comments
-
userpal almost 2 years
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 databasemysql2
in a remote server, and the Queuejobs
table is in the remote databasemysql2
, how can I configure the Queue database driver to use the remotemysql2
database? Please note that the main App is using the default database in localhost. -
userpal about 8 yearsIf you refer to this section, when we use this method
$this->dispatch($job)
, it will push jobs onto the queue (onto thejobs
table in the default database connectionmysql1
). In my case, I would like to push jobs onto thejobs
table which is in a non-default database connectionmysql2
. My main App is usingmysql1
in localhost, but my Job Queue table is inmysql2
in a remote server.