diff --git a/src/Illuminate/Database/Connection.php b/src/Illuminate/Database/Connection.php index a45c563458ad..28bbc9217d97 100755 --- a/src/Illuminate/Database/Connection.php +++ b/src/Illuminate/Database/Connection.php @@ -108,7 +108,7 @@ class Connection implements ConnectionInterface /** * The event dispatcher instance. * - * @var \Illuminate\Contracts\Events\Dispatcher + * @var \Illuminate\Contracts\Events\Dispatcher|null */ protected $events; @@ -965,7 +965,11 @@ public function beforeExecuting(Closure $callback) */ public function listen(Closure $callback) { - $this->events?->listen(Events\QueryExecuted::class, $callback); + $this->events?->listen(Events\QueryExecuted::class, function ($event) use ($callback) { + if ($event->connection === $this) { + $callback(); + } + }); } /** diff --git a/tests/Database/DatabaseConnectionTest.php b/tests/Database/DatabaseConnectionTest.php index 5b21b36fe416..5c9ba471a873 100755 --- a/tests/Database/DatabaseConnectionTest.php +++ b/tests/Database/DatabaseConnectionTest.php @@ -18,6 +18,7 @@ use Illuminate\Database\Query\Processors\Processor; use Illuminate\Database\QueryException; use Illuminate\Database\Schema\Builder; +use Illuminate\Events\Dispatcher as EventsDispatcher; use Mockery as m; use PDO; use PDOException; @@ -475,6 +476,31 @@ public function testSchemaBuilderCanBeCreated() $this->assertSame($connection, $schema->getConnection()); } + public function testConnectionListenerIsScopedToCurrentInstance() + { + $events = new EventsDispatcher(); + $mysql = (new Connection(new DatabaseConnectionTestMockPDO))->setEventDispatcher($events); + $sqlite = (new Connection(new DatabaseConnectionTestMockPDO))->setEventDispatcher($events); + $mysqlQueries = $sqliteQueries = 0; + $mysql->listen(function () use (&$mysqlQueries) { + $mysqlQueries++; + }); + $sqlite->listen(function () use (&$sqliteQueries) { + $sqliteQueries++; + }); + + $mysql->pretend(function ($connection) { + $connection->table('foo')->count(); + }); + $sqlite->pretend(function ($connection) { + $connection->table('foo')->count(); + $connection->table('foo')->count(); + }); + + $this->assertSame(1, $mysqlQueries); + $this->assertSame(2, $sqliteQueries); + } + protected function getMockConnection($methods = [], $pdo = null) { $pdo = $pdo ?: new DatabaseConnectionTestMockPDO;