Use toRawSql() to See What Eloquent Actually Runs

📖 1 minute read

When you’re debugging a complex Eloquent query, toSql() gives you the query with ? placeholders. Not super helpful when you need to paste it into your database client.

Since Laravel 10.15, you can use toRawSql() instead:

// Before — placeholders, not useful for debugging
$query->toSql();
// SELECT * FROM users WHERE status = ? AND role = ?

// After — actual values inline
$query->toRawSql();
// SELECT * FROM users WHERE status = 'active' AND role = 'admin'

Works on both the Eloquent builder and the base query builder:

// Eloquent builder
User::where('status', 'active')->toRawSql();

// Base query builder (useful for complex joins)
User::where('status', 'active')->toBase()->toRawSql();

I use ->toBase()->toRawSql() constantly when comparing old vs new query approaches during refactors. Paste both into your DB client, compare the execution plans, and you know exactly what changed.

Bonus: If you’re on an older Laravel version, the query log approach still works:

DB::enableQueryLog();
// ...run your query...
dd(DB::getQueryLog());

But toRawSql() is cleaner when you just need one query.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *