How to print query or debug queries in Laravel

We often need to debug large queries in Laravel. And laravel have built-in functions almost for everything. Here is a simple query in laravel for example.

$data = User::where(‘status’, 1)

->select(‘name’, ‘username’, ‘email’, ‘password’)

->get();

 

but we want to see the sql query. So we have to use toSql() in the place of get() and to print the query we use dd() – die and dump function of laravel, so here is out update query

$data = User::where(‘status’, 1)

->select(‘name’, ‘username’, ‘email’, ‘password’)

// ->get()

->toSql();

And dump it

dd($data);

and the output is

“SELECT ‘name’, ‘username’, ‘email’, ‘password’ FROM user WEHRE status = 1”

 

n.b.: it also can be done by DB listen

DB::listen(function($sql) {

var_dump($sql);

});

 

Here is another option with Laravel DebugBar. It’s a full featured package and gives lots on insight of the application.

 

 

——————————————————————

Reff: https://scotch.io/tutorials/debugging-queries-in-laravel