How do I get the query builder to output its raw SQL query as a string?

How do I get the query builder to output its raw SQL query as a string?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Raw SQL from Laravel Query Builders

When you construct a query using the Laravel database facade, such as DB::table('users')->get(), you are leveraging an abstraction layer designed to keep your application portable across different database engines like MySQL, PostgreSQL, or SQLite. While this abstraction handles driver-specific syntax automatically, there are moments where you need to inspect the generated SQL string before execution. This is common when debugging complex joins, optimizing performance, or logging queries for auditing purposes.

Laravel provides a straightforward method to retrieve the raw SQL string without executing it. The toSql() method on the query builder instance returns the compiled query as a string. You can access this by calling the method directly on the builder object.

Here is how you implement it:

$sql = DB::table('users')->toSql();
// $sql will contain: "SELECT * FROM users"

This approach works because Laravel's query grammar compiles the abstract syntax tree (AST) into a SQL string immediately upon calling toSql(). The resulting string is specific to the underlying database connection configured in your .env file. If you switch your environment from MySQL to SQLite, the same builder instance will generate different raw SQL if it contains dialect-specific features, though simple SELECT * statements remain identical across drivers.

Handling Bindings and Parameters

A critical distinction when working with toSql() is how Laravel handles bound values. When you pass data to a query using methods like where('status', 1) or orderBy('created_at'), these are typically stored as "bindings" rather than interpolated directly into the SQL string at definition time. This prevents SQL injection vulnerabilities and allows for dynamic value handling.

If you inspect the raw SQL string immediately after chaining conditions, you will not see the actual values. Instead, Laravel inserts a placeholder like ? or :column.

$sql = DB::table('users')
    ->where('status', 1)
    ->where('email', 'like', '%admin%')
    ->toSql();

// Output example: 
// SELECT * FROM users WHERE status = ? AND email LIKE ?

To see the final query with actual values, you must call getBindings(). This method returns an array containing the raw values associated with the placeholders in the SQL string. Note that these bindings are strictly typed based on their position in the query; mixing positional and named bindings can lead to unexpected results if not managed carefully.

$bindings = DB::table('users')
    ->where('status', 1)
    ->getBindings();

// Output example: [1, '%admin%']

Why Use toSql()?

Inspecting the raw query string is valuable for several reasons. First, it allows developers to verify that complex joins and subqueries are being translated correctly into the specific SQL dialect required by their database. Second, it facilitates debugging when a query builder method behaves unexpectedly; seeing the exact SQL sent to the driver often reveals syntax errors or logic flaws faster than inspecting the PHP object state.

However, relying solely on toSql() for logging is not recommended in production environments. The presence of binding placeholders means that logs containing only the SQL string will lack context regarding specific user inputs unless you also log the bindings alongside the query. For comprehensive auditing, it is best practice to use the database monitoring features provided by your driver or configure Laravel's query logging to capture both the statement and its parameters.

Performance Considerations

Calling toSql() does not trigger a round-trip to the database server, so it has negligible performance impact compared to executing the query. However, be mindful that compiling the SQL string happens immediately when the method is called. If you are building a dynamic application where queries change frequently based on user input, ensure you are not inadvertently caching or reusing the raw string without verifying that the bindings have been updated accordingly.

For deeper insights into how Laravel compiles queries and handles different database grammars, exploring the source code within the vendor/laravel/framework/src/Illuminate/Database directory can be educational. Understanding the grammar classes helps explain why certain methods return strings while others prepare prepared statements for execution.

Our network