Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

angelorigo's avatar

How can i get the SQL query formatted by Eloquent

Hi, I have a query created using eloquent, how can i see the real formatted query ?

0 likes
2 replies
LaryAI's avatar
Level 58

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.

1 like
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

->toRawSql()

$query = User::query()->where()->limit(1)->toRawSql();
1 like

Please or to participate in this conversation.