What's the method to obtain the raw SQL string from Laravel's query builder?

I’m working on a Laravel project and I need to see the actual SQL query that’s being generated by the query builder. Here’s what I’m trying to do:

$query = DB::table('customers')->where('active', 1)->orderBy('name');

I know this will create a query, but I want to see the raw SQL it produces before it’s executed. Something like ‘SELECT * FROM customers WHERE active = 1 ORDER BY name’.

Is there a way to get this SQL string from the query builder? I’ve looked through the docs but can’t find anything specific. It would be really helpful for debugging and understanding what’s happening under the hood.

Does anyone know if there’s a built-in method for this or if I need to use some kind of workaround? Thanks for any help!

To obtain the raw SQL string from Laravel’s query builder, you can utilize the toSql() method. Simply call this method on your query builder instance before execution. For example:

$sql = $query->toSql();

This will return the SQL string without executing the query. It’s important to note that while this method provides the SQL structure, it doesn’t include the actual parameter values. These are replaced with placeholder symbols.

If you need to see the bound parameters as well, you can access them separately using the getBindings() method:

$bindings = $query->getBindings();

Combining these two can give you a comprehensive view of your query for debugging purposes. This approach is particularly useful when optimizing complex queries or troubleshooting unexpected results.

hey, i’ve been there! u can use the toSql() method on ur query builder object. like this:

$sql = $query->toSql();

it’ll give u the raw SQL string. super helpful for debugging. just remember it won’t include the actual parameter values, but u can see those separately if needed.

ooh, interesting question! have u tried using the ‘toSql()’ method? it’s pretty nifty for peeking under the hood. but I’m curious, why do you need to see the raw sql? are u doing some performance tuning or just satisfying your inner sql geek? :smile: tell us more about ur project!