How to check the SQL of Laravel database query
Laravel provides a neat interface to access the database through
DB facade and Eloquent. But this encapsulates the underlying SQL, which really is the actual query runs on DBMS to retrieves or stores data. Though this rather simplifies the process of manipulating data, occasionally you might need to take a look at the SQL query to understand what really goes on at database level.
Quick and dirty way
One simple, quick and dirty method to see the actual SQL query is to change the name of a column in your query to something that doesn’t exist. For example, consider the following code.
Changing the name of one table column;
This throws an exception with the SQL query we want;
This works, but Laravel comes with a better approach to check the SQL of database queries.
Logging database queries
DB facade supports logging database queries with its
DB::enableQueryLog(), Laravel logs the database queries executed after enabling the query logging.
dd(DB::getQueryLog()) breaks the script execution and prints logged queries to browser.
This is fairly good enough for debugging purposes. Hope that helps.