[Solved] How do I get the query builder to output its raw SQL query as a string?

Hello dev, How Do I Get The Query Builder To Output Its Raw SQL Query, How are you in this tutorial get builder to output its raw quary as a string solution need is first is a thing.[Solved] How Do I Get The Query Builder To Output Its Raw SQL Query As A String?. i am here your solution about here

Solution 1:

Given the following code:

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

I want to get the raw SQL How Do I Get The Query Builder To Output Its Raw SQL Query string that the database query builder exicute above will generate. In this example, it would be SELECT * FROM users.

How do I do this?

Solution 2:

Use the toSql() method on a QueryBuilder instance. of the face oo..

DB::table('users')->toSql() //would return:
  • select * from `users`

This is easier than wiring up an event listener, how was the and also lets you check what the query will actually look like at any point while you’re building itThis easy.

Note: This method works for query builder or Eloquent, however toSql() is used instead of first() or get(). You cannot run the query and also get the SQL at the same time using this method.

Solution 3:

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

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

// Your Eloquent query run by using get()

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

You will have something like that:

array(1) {

  [0]=>
  array(3) {

    ["query"] =>
 string(21) "select * from "users""
    ["bindings"]=>array(0) {
             
      }
    ["time"] => string(4) "0.92"
  }

}

Solution 4:

You can listen to the ‘illuminate.query’ event caliing. Before the query add the following event listener:

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

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

This will print out something like:

array(4) {
  [0]=>
    string(21) "select * from "users""
  [1]=>
    array(0) {
  }
  [2]=>
    string(4) "1245"
  [3]=>
    string(6) "love"
}

Summary

It’s all About this issue. Hope all solution helped you a lot. Comment Added Your thoughts and your dev queries. Also, Comment below Fill-up form which solution worked with you?

Leave a Comment