[solved] – How do I get the query builder to output in raw as string – 9

Sometimes, you ask yourself how you can get the Laravel query builder to output its raw SQL query as a string. Luckily, there are multiple, I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM all_users.

Given the following code of : How do I get the query builder to output in raw as string

How do I get the query builder to output in raw as string

Given the following code:

DB::table('all_users')->get();

How do I do this?

To output to the screen the last queries run you can use this:

Solution 1:

DB::enableQueryLog(); // Enable query log

Solution 2:

// Your Eloquent query executed by using get()

dd(DB::getQueryLog()); // Show results of log

You will Have Like Output:

array(1) {
  [0]=>
  array(3) {
    ["query"]=>
    string(21) "select * from "all_users""
    ["bindings"]=>
    array(0) {
    }
    ["time"]=>
    string(4) "0.78"
  }
}

Solution 3:

Event::listen('illuminate.query', function($query, $params, $time, $conn) 
{ 
    dd(array($query, $params, $time, $conn));
});

DB::table('all_users')->get();

Output 3:

array(4) {
  [0]=>
  string(21) "select * from "all_users""
  [1]=>
  array(0) {
  }
  [2]=>
  string(4) "0.78"
  [3]=>
  string(6) "sqlite"
}

Solution 4:

Laravel Project If:
\Illuminate\Database\Capsule\Manager::getQueryLog();

EDIT AGAIN

$sql = $query->toSql();
$bindings = $query->getBindings();

Solution of Only “toSql()”

in my case:

 DB::table('all_users')->toSql(); 

return now:

select * from users

Leave a Comment