How can I retrieve the raw SQL string from a database query builder?

I’m working with a query builder and need to see the actual SQL statement it creates before execution.

Here’s my current code:

$result = QueryBuilder::from('customers')->fetch();

I want to extract the raw SQL string that this query builder will produce. For this example, the expected output should be SELECT * FROM customers.

What’s the best approach to accomplish this? I need to debug my queries and want to see exactly what SQL is being generated behind the scenes.

yep, you’re right! most query builders have built-in debug methods. you can usually call ->toSql() or ->getSql() before fetching results. also, some have a __toString() method which can show the sql when you echo the builder object directly.

Most query builders expose the SQL through a dedicated method, though the exact name varies by implementation. In your case, try calling QueryBuilder::from('customers')->getSql() or QueryBuilder::from('customers')->toString() instead of fetch(). Another common approach is enabling query logging at the database connection level, which captures all executed queries with their parameters. I’ve found this particularly useful when dealing with complex queries involving joins or subqueries. Some builders also support a debug mode that automatically outputs the SQL to your error log or console before execution.

hmm interesting question! what query builder are you actually using tho? different ones have diffrent methods - like some use toSql() or getRawSql(). are you working with laravel’s eloquent, doctrine, or something custom? might help narrow down the exact method you need!