How to Get Raw SQL Query From Eloquent & Query Builder
Let’s look at how we can get the raw SQL query from an Eloquent Model and Query Builder in just a few steps.
Get raw SQL query from an Eloquent Model
Here we have a simple query using the Eloquent Model.
We make use of
DB::enableQueryLog() to enable the query log.
Then die and dump the
DB::getQueryLog() that will give us detailed information about the query and its execution time.
The query has the ID data bound, and the log makes it easy to get the value of the binding. In this case, it’s 29.
As a side note, we can log as many queries as we want.
Get raw SQL query from Query Builder
Here we have the same query as the one above.
To get the raw SQL we can use the
We got the raw query but we’re missing the data binding, which sucks.
Let’s fix that.
That was it!
Happy coding 😊
Let me know what you think about this article through comments below, or on Twitter at @pelu_carol.
If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.