Patrick Maciel Patrick Maciel - 11 days ago 6
PHP Question

Get the query executed in Laravel 3/4

How can I get the executed query in Laravel 3/4, using Fluent Query Builder or Eloquent ORM.

For example:

DB::table('users')->where_status(1)->get();


Or
(posts (id, user_id, ...))


User::find(1)->posts->get();


Or... How I can save in log, all queries executed.

Answer

Laravel 4

In Laravel 4, you have to call DB::getQueryLog() to get all ran queries.

$queries = DB::getQueryLog();
$last_query = end($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.


Laravel 3

In Laravel 3, you can get the last executed query from an Eloquent model calling the static method last_query on the DB class.

DB::last_query();

This, however, requires that you enable the profiler option in application/config/database.php. Alternatively you could, as @dualed mentioned, enable the profiler option, in application/config/application.php or call DB::profile() to get all queries ran in the current request and their execution time.