Author: Daryle De Silva

  • Use toRawSql() to See What Eloquent Actually Runs

    Use toRawSql() to See What Eloquent Actually Runs

    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.