Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Eloquent: How to get raw sql that is being executed? (with binded data)

Im trying to figure out how to get the raw sql query being executed including the binded data in it. Here is what ive got:

\DB::connection()->enableQueryLog();
$query = \DB::getQueryLog();
$lastQuery = end($query);

And here is what the result looks like:

array(3) {
  ["query"]=>
  string(57) "select * from `table_1` where `field_1` = ? limit 1"
  ["bindings"]=>
  array(1) {
    [0]=>
    string(34) "xyz"
  }
}

So how do I get a dump of a full sql query like this (the good old fashioned way)?

select * from `table_1` where `field_1` = 'xyz' limit 1

Thanks

like image 861
Raheel Hasan Avatar asked Sep 01 '16 11:09

Raheel Hasan


1 Answers

You may want to check out the Laravel debugbar. I wouldn't develop a Laravel app without it. It will give you a breakdown of all queries (including repeated queries and ajax queries), with the speed they executed at and a note to the line in the controller/method that called them. (It provides TONS more info as well, such as views, gates, routes, etc.)

Also, Laravel has a toSql() method that you can use instead of your example. It will only show you the prepared statement as your example does, but it's at least a little cleaner. If you use toSql(), you have to apply it before you execute the query though.

$foo = Foo::where('bar', 'baz');
$foo_sql = $foo->toSql();
$foo->get();
like image 77
snipe Avatar answered Nov 12 '22 12:11

snipe