How to output the raw SQL query in Laravel

How to output the raw SQL query in Laravel

Written by Cody Jenson on Jan 10th, 2023 Views Report Post

Table of contents

Laravel does a lot of magic behind the scenes when fetching data from the database. Luckily there are some really easy ways to get the raw SQL query so that you can understand everything that's going on behind the scenes. Let me show you how to do this in a few examples.

Fetching a user from the DB

Using Eloquent we can easily fetch a specific user with the following query:

$user = User::where('email', '[email protected]')->first();

Now, if we wanted to see the query that was being called, instead of calling the first() method, we could replace that with toSql():

$user = User::where('email', '[email protected]')->toSql();

If we were to output the code above using a dd($user) command, we would see the following output:

"select * from `users` where `email` = ?"

This is excellent because now we can see the underlying raw SQL query from any of our Eloquent calls.

This was obviously a very simple example, but I hope you can see how helpful this can be when you need to debug a query that's not returning the right results.

You may also want to checkout the following post by BeyondCode to learn more about outputting the query for any Eloquent method

Happy coding ✌️

Comments (0)