Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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 toSQL() method.

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.



This post first appeared on Neutron Dev, please read the originial post: here

Share the post

How to Get Raw SQL Query From Eloquent & Query Builder

×

Subscribe to Neutron Dev

Get updates delivered right to your inbox!

Thank you for your subscription

×