Raw Query Output With Bindings is Coming to Laravel 10
Published on by Paul Redmond
Laravel 10 is getting a long-awaited feature to get the raw SQL query, including bindings 🥳:
With previous patches being merged into Laravel, I was now able to create one that has been requested for quite some years:
— Tobias_Petry.sql (@tobias_petry) June 20, 2023
User::where(...)->ddRawSql()
It prints the generated SQL query *with* bindings embedded safely into the query 🤯https://t.co/3lSfaGooKH
This feature will be part of the next tagged v10.x
release, which usually happens weekly:
// Using the new `toRawSql()` methodUser::where('email', 'foo@example.com')->toRawSql();// "SELECT * FROM users WHERE email = 'foo@example.com'"
There is some prior art before toRawSql()
—various developer tools (i.e., Laravel Debugbar) give you queries, and there's a dd()
method you can use as well:
// Using the dd() methodUser::where('email', 'foo@example.com')->dd();// "SELECT * FROM users WHERE email = ?"// [// 0 => "foo@example.com"// ]
The dd()
feature is nice, and gives you everything you need. However, you have to manually copy/paste/insert the bindings if you want to re-run, explain, and otherwise debug the query. The new toRawSql()
can help with that need to copy the query and run it directly in a database client.
Thanks to Tobias Petry, who contributed to this PR; he has also been contributing important database updates to Laravel. For example, he recently contributed escaping functionality within grammar which was released with Laravel 10.13.
For more details on the upcoming toRawSql()
method, check out Pull Request #47507—this is a fantastic quality-of-life feature!