How to get the raw SQL query from the Laravel Query Builder
In this post we will give you information about How to get the raw SQL query from the Laravel Query Builder. Hear we will give you detail about How to get the raw SQL query from the Laravel Query Builder And how to use it also give you demo for it if it is necessary.
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.
Also see: Importing large CSV files in MySQL using Laravel
. .
Hope this code and post will helped you for implement How to get the raw SQL query from the Laravel Query Builder. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs