Access raw SQL queries from the database query builder
Laravel’s database query builder provides a convenient way to build SQL queries. However, it might be useful to get the raw SQL query string it will generate. This is useful for troubleshooting or creating vendor-agnostic queries.
Use toSql() method
To get the raw SQL query, use the toSql() method on the QueryBuilder instance. For example:
<code class="language-php">$query = DB::table('users'); $sql = $query->toSql();</code>
This will return the raw SQL query string, for example:
<code class="language-sql">select * from `users`</code>
Advantages over event listeners
Previously, it was recommended to use event listeners to capture raw SQL queries. However, the toSql() method is simpler and avoids the need to connect event listeners. It also lets you check how your query looks at any stage of the build.
Limitations
Please note that the toSql() method does not execute the query. If you need to both run the query and get the SQL, you cannot use this method.
The above is the detailed content of How Can I Access the Raw SQL Query from Laravel's Database Query Builder?. For more information, please follow other related articles on the PHP Chinese website!