Laravel get SQL query


This post goes over how to get Laravel SQL query.

Prerequisites

Let’s say you have a query:

use Illuminate\Support\Facades\DB;

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

toSQL

Call toSql() to get the SQL:

DB::table('users')->where('id', 1)->toSql();
// "select * from `users` where `id` = ?"

Call getBindings() to get the bindings:

DB::table('users')->where('id', 1)->getBindings();
// = [1]

enableQueryLog

Get query log:

DB::enableQueryLog();
DB::table('users')->where('id', 1)->get();
DB::getQueryLog();

Log output:

[
  [
    "query" => "select * from `users` where `id` = ?",
    "bindings" => [
      1,
    ],
    "time" => 13.37,
  ],
]


Please support this site and join our Discord!