You might occasionally ask how to output the original SQL query from the Laravel query builder as a string. Thankfully, there are a few different ways to get this raw query in Laravel.
When troubleshooting problems with the Laravel query builder, you might wish to see the actual SQL query that is being executed for debugging purposes.
How to get the raw SQL query from the Laravel Query Builder
Here are some simple methods you can employ to immediately force the query Builder to publish its original SQL query as a string.
1. Using Laravel Eloquent methods
The query from an Eloquent call can first be obtained using the toSql()
method. If you only want the query and don't want to update any data. This function is helpful because it returns the query without running it. However, this approach won't show the whole query if it's complicated or contains sub-queries.
User::query()
->where('created_at', '<', now()->subYear())
->toSql();
Output:
select * from `users` where `created_at` < ?
2. Using the Laravel Query Log
The second method uses the Laravel query log, which aggregates every query inside a request. Run your query, turn on this log, and dump the outcomes.
\DB::enableQueryLog();
User::query()
->where('created_at', '<', now()->subYear())
->toSql();
dd(\DB::getQueryLog());
You may see here particular information about the query that was run and how long it took to complete. It is straightforward to validate your data because data bindings are reported in the query logs if a query has them.
Thank you for reading this article.