To see the SQL query generated by an Eloquent query in Laravel, you can use the toSql() method. This method will return the SQL query as a string, with placeholders for bindings. Here's an example:
$query = User::where('status', 'active')->toSql();
echo $query;
This will output something like:
select * from `users` where `status` = ?
If you want to see the query with the actual bindings, you can use the getBindings() method to retrieve the bindings and then manually replace them in the query string. Here's a simple way to do that:
$query = User::where('status', 'active');
$sql = str_replace_array('?', $query->getBindings(), $query->toSql());
echo $sql;
To use str_replace_array, you might need to define it if it's not available in your version of Laravel. Here's a simple implementation:
if (!function_exists('str_replace_array')) {
function str_replace_array($search, array $replace, $subject) {
foreach ($replace as $value) {
$subject = preg_replace('/' . preg_quote($search, '/') . '/', $value, $subject, 1);
}
return $subject;
}
}
Alternatively, if you want to see all queries executed by your application, you can enable query logging in Laravel. Add the following to your AppServiceProvider's boot method:
use Illuminate\Support\Facades\DB;
public function boot()
{
DB::listen(function ($query) {
\Log::info(
$query->sql,
$query->bindings,
$query->time
);
});
}
This will log all executed queries to your application's log file, including the bindings and execution time.