How to print query in laravel

In Laravel, you can print the SQL query generated by Eloquent or the Query Builder using a few different methods, depending on the situation.

How to print query in laravel Image

✅ 1. Use toSql() Method (for getting SQL without executing)

$query = DB::table('users')->where('id', 1);
dd($query->toSql());

Output:

select * from `users` where `id` = ?

This will show the raw SQL with placeholders, not the actual values.


✅ 2. Use dd() or dump() After Adding ->get() or ->first()

$users = DB::table('users')->where('id', 1)->get();
dd($users);

This executes the query and dumps the result. But doesn't show the SQL itself.


✅ 3. Enable Query Logging (to see actual queries with bindings)

DB::enableQueryLog();

// Run some queries...
$users = DB::table('users')->where('id', 1)->get();

// Show logged queries
dd(DB::getQueryLog());

This shows full queries with bindings merged in.


✅ 4. Use DB::listen() for Logging Queries (e.g., in Service Providers)

In AppServiceProvider or anywhere during booting:

use Illuminate\Support\Facades\DB;

public function boot()
{
    DB::listen(function ($query) {
        logger($query->sql);
        logger($query->bindings);
        logger($query->time);
    });
}

✅ 5. Print Eloquent Queries

$userQuery = User::where('email', 'test@example.com');
dd($userQuery->toSql());

Or with bindings:

$query = User::where('email', 'test@example.com');
dd([$query->toSql(), $query->getBindings()]);

6. Print fully interpolated SQL queries in Laravel

// Create custom helper function
function interpolateQuery($query, $bindings) {
    $pdo = DB::getPdo();
    foreach ($bindings as $i => $binding) {
        $bindings[$i] = $pdo->quote($binding);
    }
    return vsprintf(str_replace('?', '%s', $query), $bindings);
}

$query = DB::table('users')->where('id', 1);
$sql = interpolateQuery($query->toSql(), $query->getBindings());

dd($sql);

Note:

  • Be cautious with this method in production, as it exposes query details.

Summary

MethodUse CaseNotes
toSql()See SQL with ? placeholdersNo bindings
getQueryLog()Get full SQL with bindingsUse after enableQueryLog()
DB::listen()Log queries in real-timeGood for debugging
->get() or ->first() + dd()Get resultDoesn't show query

 Happy Coding! 😊

Do you Like?