How can I retrieve the raw executed SQL query in Laravel 3/4 using Laravel Query Builder or Eloquent ORM?
For example, something like this:
DB::table('users')->where_status(1)->get();
Or:
(posts (id, user_id, ...))
User::find(1)->posts->get();
Otherwise, at the very least how can I save all queries executed to laravel.log?
I would recommend using the Chrome extension Clockwork with the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.
Laravel 4+
In Laravel 4 and later, you have to call
DB::getQueryLog()
to get all ran queries.Or you can download a profiler package. I'd recommend barryvdh/laravel-debugbar, which is pretty neat. You can read for instructions on how to install in their repository.
Note for Laravel 5 users: You'll need to call
DB::enableQueryLog()
before executing the query. Either just above the line that runs the query or inside a middleware.Laravel 3
In Laravel 3, you can get the last executed query from an
Eloquent
model calling the static methodlast_query
on theDB
class.This, however, requires that you enable the
profiler
option inapplication/config/database.php
. Alternatively you could, as @dualed mentioned, enable theprofiler
option, inapplication/config/application.php
or callDB::profile()
to get all queries ran in the current request and their execution time.You can enable the "Profiler" in Laravel 3 by setting
In your
application/config/application.php
andapplication/config/database.php
This enables a bar at the bottom of each page. One of its features is listing the executed queries and how long each one took.
Here is a quick Javascript snippet you can throw onto your master page template. As long as it's included, all queries will be output to your browser's Javascript Console. It prints them in an easily readable list, making it simple to browse around your site and see what queries are executing on each page.
When you're done debugging, just remove it from your template.
L4 one-liner
(which write query):
$q=\DB::getQueryLog();dd(end($q));
Since the profiler is not yet out in Laravel 4, I've created this helper function to see the SQL being generated:
NOTE: Set the $all flag to false if you only want the last SQL query.
I keep this sort of functions in a class called DBH.php (short for Database Helper) so I can call it from anywhere like this:
Here is the output I get:
In case you are wondering, I use Kint for the dd() formatting. http://raveren.github.io/kint/