Method 1: Get raw SQL using toSql()
<?php DB::table('posts')->toSql()
select * from `posts`
Do note that this method works for Query Builder or Eloquent, however toSql() is used instead of first() or get(). You cannot run the query and also get the SQL at the same time using this method.
Method 2: Get raw SQL using Query Log
The second method is to use the "enableQueryLog()" method of the "DB" facade and it looks as follows.
<?php DB::enableQueryLog(); // Enable query log // Write your query here dd(DB::getQueryLog()); // Show results of log
array(1) { [0]=> array(3) { ["query"]=> string(21) "select * from "users"" ["bindings"]=> array(0) { } ["time"]=> string(4) "0.92" } }
Method 3: Using Event Listener
The third method is to listen to the "illuminate.query" event and you can define it like below.
<?php Event::listen('illuminate.query', function($query, $params, $time, $conn) { dd(array($query, $params, $time, $conn)); });
Method 4: Using dump method
For the fourth method, you can make use of the "dump" method to chain the query. This method is available as of Laravel 5.8.15 and the query builder now has dd and dump methods.
<?php DB::table('posts')->where('slug', 'hello-world')->dump();
Method 5: Using Debugbar Extension
The fifth method is to use the Laravel Debugbar. This extension is a package that can be installed through the composer package manager.
composer require barryvdh/laravel-debugbar
Other Mentions
One other way is to make use of Laravel Clockwork and which is similar to Laravel Debugbar. You can preview your raw SQL query from within the debug page.
Conclusion
By now you should be able to get the raw SQL query from Laravel Query Builder. If you find this snippet to be helpful do make sure to share it with your friends and cheers. If you have any feedback do start a new discussion from the comment box below.
Leave a reply