DEV Community

TRUNG VU
TRUNG VU

Posted on

2

How to get raw sql that is being executed with binded data

Sometime we need to print executed queries in Laravel application for debug, I will give methods of how to show it.

Method 1

In controller:

$posts = Post::whereActive(1);
dd($posts->toSql(), $posts->getBindings());
Enter fullscreen mode Exit fullscreen mode

Output:

"select * from `posts` where `status` = ?"

array:1 [▼
  0 => 1
]
Enter fullscreen mode Exit fullscreen mode

Method 2

In controller:

DB::enableQueryLog();
$posts = Post::active()->paginate(5);
$query = DB::getQueryLog();
dd($query);
Enter fullscreen mode Exit fullscreen mode

Output:

array:2 [▼
  0 => array:3 [▼
    "query" => "select count(*) as aggregate from `posts` where `status` = ?"
    "bindings" => array:1 [▼
      0 => 1
    ]
    "time" => 0.3
  ]
  1 => array:3 [▼
    "query" => "select * from `posts` where `status` = ? limit 5 offset 0"
    "bindings" => array:1 [▼
      0 => 1
    ]
    "time" => 0.3
  ]
]
Enter fullscreen mode Exit fullscreen mode

Method 3

In controller:

use Illuminate\Support\Facades\DB;

DB::listen(function ($query) {
    dump($query->sql,$query->bindings);
});
$post = Post::ofSlug($slug)->active()->firstOrFail();
Enter fullscreen mode Exit fullscreen mode

Output:

"select * from `posts` where `slug` = ? and `status` = ? limit 1"

array:2 [▼
  0 => "create-custom-helper-class-in-laravel-7"
  1 => 1
]
Enter fullscreen mode Exit fullscreen mode

Happy Coding :)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay