diff --git a/src/Illuminate/Database/Events/QueryExecuted.php b/src/Illuminate/Database/Events/QueryExecuted.php index 833a21e6f984..644d947332c3 100644 --- a/src/Illuminate/Database/Events/QueryExecuted.php +++ b/src/Illuminate/Database/Events/QueryExecuted.php @@ -56,4 +56,17 @@ public function __construct($sql, $bindings, $time, $connection) $this->connection = $connection; $this->connectionName = $connection->getName(); } + + /** + * Get the raw SQL representation of the query with embedded bindings. + * + * @return string + */ + public function toRawSql() + { + return $this->connection + ->query() + ->getGrammar() + ->substituteBindingsIntoRawSql($this->sql, $this->connection->prepareBindings($this->bindings)); + } } diff --git a/tests/Database/DatabaseIntegrationTest.php b/tests/Database/DatabaseIntegrationTest.php new file mode 100644 index 000000000000..ab32d3094784 --- /dev/null +++ b/tests/Database/DatabaseIntegrationTest.php @@ -0,0 +1,38 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); + $db->setAsGlobal(); + $db->setEventDispatcher(new Dispatcher); + } + + public function testQueryExecutedToRawSql(): void + { + $connection = DB::connection(); + + $connection->listen(function (QueryExecuted $query) use (&$queryExecuted): void { + $queryExecuted = $query; + }); + + $connection->select('select ?', [true]); + + $this->assertInstanceOf(QueryExecuted::class, $queryExecuted); + $this->assertSame('select ?', $queryExecuted->sql); + $this->assertSame([true], $queryExecuted->bindings); + $this->assertSame('select 1', $queryExecuted->toRawSql()); + } +}