Printing raw SQL queries with bindings in Laravel 10.x
Perhaps the most anticipated feature that all Laravel developers were waiting for is finally going to be available in the framework. Yes, I’m talking about the ability to print raw SQL queries with bindings in Laravel 10.x.
Laravel 10.x is going to introduce a new
toRawSql()
method that will allow you to print the raw SQL queries with bindings. This is going to be a great addition to the framework as it will help you debug your queries more easily.
So, for instance, you can print the raw SQL for the following Eloquent query with bindings like so,
$books = Book::where('author', 'Ruskin Bond')
where('published', true)
->toRawSql();
dd($books);
This will print the following output.
select * from `books`
where `author` = 'Ruskin Bond'
and `published` = 1
You can directly print raw queries by using the supplementary ddRawSql()
/dumpRawSql()
methods like so.
Book::where('author', 'Ruskin Bond')
where('published', true)
->ddRawSql();
// select * from `books`
// where `author` = 'Ruskin Bond'
// and `published` = 1
Book::where('author', 'Ruskin Bond')
where('published', true)
->dumpRawSql();
// select * from `books`
// where `author` = 'Ruskin Bond'
// and `published` = 1
This is pretty handy since previously if you dd()
‘d an Eloquent query, it would print the query with bindings like so,
$books = Book::where('author', 'Ruskin Bond')
where('published', true)
->dd();
dd($books);
This would print the following output.
"select * from `books`
where `author` = ?
and `published` = ?"
array:2 [
0 => "Ruskin Bond"
1 => true
]
As you can see, in this case, you would have to manually replace the bindings with the actual values to run the query in your database client. But with the toRawSql()
method, you don’t have to do that anymore!
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.