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

Aktheon's avatar

Printing raw SQL string formed by Query Builder

Hello. I'm trying to understand how query builder is forming SQL requests, messing with DB::selectRaw(...)->where(...)->whereRaw(...) ; and joinSub(..) (subqueries) I'm trying to do less Raw inputs as possible, but to do so in proper way i have to understand how Query builder is forming it's queries: when it adds extra symbols/words and where.

IMHO, the best way to understand Query builder logic is to print formed query string (but not it's result). is there any way i can see how query looks like for request?

DB::table('cities')->select(DB::raw('CityName, (SELECT MAX(Area) FROM city_areas)'))->where('Translit', $c)

0 likes
2 replies
manelgavalda's avatar

You can use DB::getQueryLog(). Just wrap the queries you want to track, like this:

\DB::enableQueryLog();
\App\User::first(); // Your queries
dd(\DB::getQueryLog());

You will see this:

  0 => array:3 [
    "query" => "select top 1 * from [T2102_Usuari]"
    "bindings" => []
    "time" => 174.56
  ]
Aktheon's avatar
Aktheon
OP
Best Answer
Level 1

i've found a better solution:

dd(
DB::table('cities')->select(DB::raw('CityName, (SELECT MAX(Area) FROM city_areas)'))->where('Translit', $c)->toSql()
);

->toSql() is easier way to do so and do not rely on server response. Even if you've made a mistake in your request you'll still be able to get a request string

Please or to participate in this conversation.