Get the Query Builder Raw SQL as a String

If you're writing a complex query with the Laravel Query Builder, you might be curious to see the actual query in raw SQL.

Fortunately there's a function for this and it can return it as a string, so you see exactly what you're doing before sending it to the database or setting up an Event Listener, which is much more complicated.

How to get the raw SQL as a string

The Query Builder function we will need is toSql(), that will just return the raw SQL as a string, without running it.

You can use the function like this:

$rawSQL = DB::table('your-table')->toSql();

Now $rawSQL will return something like this:

select * from `your-table`

This is really recommended to use after any complex query built with Query Builder, as it can save you from a lot of trouble.