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.

DB::table('users')
    ->join('permissions', 'permissions.entity_id', '=', 'users.id')
    ->where('permissions.ability_id', 5)
    ->get();

Changing the name of one table column;

DB::table('users')
    ->join('permissions', 'permissions.entity_id', '=', 'users.id')
    ->where('permissions.ability_idx', 5) // ability_id to ability_idx
    ->get();

This throws an exception with the SQL query we want;

exception

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() and DB::getQueryLog() functions.

DB::enableQueryLog();
DB::table('users')
    ->join('permissions', 'permissions.entity_id', '=', 'users.id')
    ->where('permissions.ability_idx', 5) // ability_id to ability_idx
    ->get();
dd(DB::getQueryLog());

With 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.

array:1 [
  0 => array:3 [
    "query" => "select * from `users` inner join `permissions` on `permissions`.`entity_id` = `users`.`id` where `permissions`.`ability_id` = ?"
    "bindings" => array:1 [
      0 => 5
    ]
    "time" => 0.31
  ]
]

This is fairly good enough for debugging purposes. Hope that helps.

Saranga
Saranga A web developer and highly passionate about research and development of web technologies around PHP, HTML, JavaScript and CSS.
comments powered by Disqus