Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?