Home > Backend Development > PHP Tutorial > How Can I Get the Raw SQL Query from Laravel's Query Builder?

How Can I Get the Raw SQL Query from Laravel's Query Builder?

Susan Sarandon
Release: 2024-12-11 04:38:09
Original
678 people have browsed it

How Can I Get the Raw SQL Query from Laravel's Query Builder?

Getting the Raw SQL Query from the Query Builder

In Laravel, the query builder provides a convenient way to build database queries using a fluent interface. However, there may be instances when you need to retrieve the raw SQL query that the query builder generates. This can be useful for debugging or various other purposes.

To obtain the raw SQL query, use the toSql() method on a QueryBuilder instance. For example:

$sql = DB::table('users')->toSql();
Copy after login

This will return the raw SQL query string, such as:

select * from `users`
Copy after login

The toSql() method is available for both the query builder and Eloquent models. In the case of Eloquent models, use ->toSql() instead of ->first() or ->get().

Important Note:

While the toSql() method allows you to retrieve the raw SQL query, it's important to note that it doesn't execute the query. If you want to execute the query and retrieve the results, you should still use ->first() or ->get().

The above is the detailed content of How Can I Get the Raw SQL Query from Laravel's Query Builder?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template