Generate The Raw MySQL Query From Laravel Query Builder

Generate The Raw MySQL Query From Laravel Query Builder

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

Stefan Bogdanescu

Founder & Senior Architect

Extracting Raw MySQL Queries from Laravel Query Builder

Laravel's Query Builder abstracts SQL syntax into an elegant, chainable interface. While this abstraction speeds up development and reduces boilerplate, it occasionally becomes a liability when you need to inspect what is actually being sent to the database. Debugging complex joins or optimizing performance often requires seeing the raw SELECT, INSERT, or UPDATE statement rather than the fluent syntax. Fortunately, Laravel provides built-in mechanisms to retrieve this underlying SQL without needing to switch frameworks or manually parse strings.

Using the toSql() Method

The most direct way to convert a query builder instance into a raw string is by calling the toSql() method. This method returns the generated SQL statement as a plain string, stripping away all Laravel's model binding and magic methods.

Consider a typical user retrieval scenario:

$query = App\User::where('balance', '>', 0)->where('status', 'active')->get();

To get the raw MySQL query from this object, you would invoke toSql() before executing the query:

$sql = $query->toSql();
// Result: "SELECT * FROM `users` WHERE `balance` > ? AND `status` = ?"

Note that toSql() only returns the SQL string; it does not execute the query. If you attempt to call get() or first() on a model collection derived from this, you must ensure the raw SQL isn't mixed with eager loading logic unexpectedly. The method is particularly useful when logging queries for auditing purposes or debugging complex conditions where the generated WHERE clause might differ from your initial mental model.

Handling Bindings and Parameters

A critical detail when inspecting raw queries is understanding how parameters are handled. When you use placeholders like ? in the SQL string returned by toSql(), Laravel does not replace them with actual values immediately. Instead, it prepares the statement using prepared statements, which protects against SQL injection by separating code from data.

If you need to see the fully resolved query for analysis (for example, to paste into a database client like MySQL Workbench), you must manually bind the values yourself or use Laravel's debugging tools. However, be cautious: replacing placeholders with actual values in a production environment can reintroduce injection vulnerabilities if not handled strictly.

Using dumpBindings() for Full Context

Sometimes knowing just the SQL string isn't enough; you need to see how the bindings map to those placeholders. The dumpBindings() method (available in newer Laravel versions) or manual binding inspection helps clarify this. You can combine this with toSql() to get a complete picture:

$sql = App\User::where('balance', '>', 0)->toSql();
$bindings = App\User::where('balance', '>', 0)->getBindings();

// Manual reconstruction for debugging
echo $sql . PHP_EOL;
print_r($bindings);

This approach is invaluable when troubleshooting why a query returns no results. Perhaps the expected value isn't being passed correctly, or the placeholder order doesn't match your assumption.

Performance and Debugging Trade-offs

While inspecting raw SQL is powerful, it should not replace proper debugging tools. Laravel offers DB::enableQueryLog() to capture executed queries in a static array accessible via DB::getQueryLog(). This logs every query that actually ran against the database, including bindings and execution time, without requiring you to manually call toSql() for each operation.

However, enabling the query log can impact performance in high-traffic applications because it involves serialization of large query strings into memory. Use it sparingly, perhaps within a specific route or middleware block, rather than globally.

When to Use Which Approach

Use toSql() when you are building a dynamic query and need to preview its structure before execution. This is common in admin panels where you might generate queries based on user filters and want to log them for later review.

Use getQueryLog() when analyzing performance bottlenecks or debugging unexpected behavior in existing codebases. It provides a comprehensive view of what the application actually did, not just what one specific query builder instance would do.

By leveraging these tools, you maintain the benefits of Laravel's abstraction while retaining the ability to dive deep into the underlying SQL when necessary. For deeper insights into Laravel's query internals or advanced debugging strategies, resources like https://laravelcompany.com offer comprehensive guides on optimizing application performance and understanding the ORM layer.

Our network