Sometimes we need Raw SQL query to debug the complex SQL statements and more. But by default, Laravel does not provide this facility. I am familiar with 3 methods that can help you get Raw SQL query from the Query Builder.
1. To use toSql() method
Let’s take a simple example. Find the user who has id 1 and country IN in User Model.
$user = DB::table('users')->where('id', 1)->where('country', 'IN')->first();
dd($user);
The above code will show you user result. But now if you add the toSql() method in place fo first() then you will get the Raw SQL query.
$user = DB::table('users')->where('id', 1)->where('country', 'IN')->toSql();
dd($user);
But there is a problem with the toSql() method. It won’t display the passed value to the Query Builder or Model.
2. Enable Query Log
Second option is by enabling Query Log.
DB::enableQueryLog();
$user = DB::table('users')->where('id', 1)->where('country', 'IN')->toSql();
dd(DB::getQueryLog());
3. Using Laravel Debugbar
The third and most recommended option is by installing the Laravel Debugbar by the composer. It will provide you a detailed view of each and every query.
composer require barryvdh/laravel-debugbar
If you familiar with other option to get Raw SQL query then please share it through comments.