Tags
Asked 3 years ago
17 Jun 2021
Views 197
Maiya

Maiya posted

How do I get the query builder to output its raw SQL query as a string

How do I get the query builder to output its raw SQL query as a string
shabi

shabi
answered Apr 27 '23 00:00

To get the query builder to output its raw SQL query as a string in Laravel, you can use the toSql() method. Here's an example:


$query = DB::table('users')
             ->select('id', 'name')
             ->where('age', '>', 18)
             ->orderBy('name')
             ->get();

$sql = $query->toSql();

echo $sql;

In this example, we build a query using the Laravel query builder that selects the id and name columns from the users table where the age is greater than 18, and orders the results by name. Then, we call the toSql() method on the query builder instance to get the raw SQL query as a string and store it in the $sql variable. Finally, we output the raw SQL query to the screen using the echo statement.

Note that the to Sql() method returns the raw SQL query as a string, but does not execute the query. To execute the query and retrieve the results, you need to call one of the query execution methods like get(), first(), or paginate().
Post Answer