[php] Get the Query Executed in Laravel 3/4

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?

This question is related to php laravel orm eloquent laravel-query-builder

The answer is


For Laraver 4 it's

DB::getQueryLog()

Using the query log doesnt give you the actual RAW query being executed, especially if there are bound values. This is the best approach to get the raw sql:

DB::table('tablename')->toSql();

or more involved:

$query = Article::whereIn('author_id', [1,2,3])->orderBy('published', 'desc')->toSql();
dd($query);

Or as alternative to laravel 3 profiler you can use:

https://github.com/paulboco/profiler or https://github.com/barryvdh/laravel-debugbar


I would recommend using the Chrome extension Clockwork with the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.

Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts, including information on request, headers, GET and POST data, cookies, session data, database queries, routes, visualisation of application runtime and more. Clockwork includes out of the box support for Laravel 4 and Slim 2 based applications, you can add support for any other or custom framework via an extensible API.

enter image description here


Laravel 5

Note that this is the procedural approach, which I use for quick debugging

    DB::enableQueryLog();

    // Run your queries
    // ...

    // Then to retrieve everything since you enabled the logging:
    $queries = DB::getQueryLog();
    foreach($queries as $i=>$query)
    {
        Log::debug("Query $i: " . json_encode($query));
    }

in your header, use:

     use DB;
     use Illuminate\Support\Facades\Log;

The output will look something like this (default log file is laravel.log):

[2015-09-25 12:33:29] testing.DEBUG: Query 0: {"query":"select * from 'users' where ('user_id' = ?)","bindings":["9"],"time":0.23}

***I know this question specified Laravel 3/4 but this page comes up when searching for a general answer. Newbies to Laravel may not know there is a difference between versions. Since I never see DD::enableQueryLog() mentioned in any of the answers I normally find, it may be specific to Laravel 5 - perhaps someone can comment on that.


There is very easy way to do it, from your laravel query just rename any column name, it will show you an error with your query.. :)


To get the last executed query in laravel,We will use DB::getQueryLog() function of laravel it return all executed queries. To get last query we will use end() function which return last executed query.

$student = DB::table('student')->get();
$query = DB::getQueryLog();
$lastQuery = end($query);
print_r($lastQuery);

I have taken reference from http://www.tutsway.com/how-to-get-the-last-executed-query-in-laravel.php.


You can also listen for query events using this:

DB::listen(function($sql, $bindings, $time)
{
    var_dump($sql);
});

See the information from the docs here under Listening For Query Events


in Laravel 4 you can actually use an Event Listener for database queries.

Event::listen('illuminate.query', function($sql, $bindings)
{
    foreach ($bindings as $val) {
        $sql = preg_replace('/\?/', "'{$val}'", $sql, 1);
    }

    Log::info($sql);
});

Place this snippet anywhere, e.g. in start/global.php. It'll write the queries to the info log (storage/log/laravel.log).


L4 one-liner

(which write query):

$q=\DB::getQueryLog();dd(end($q));


The Loic Sharma SQL profiler does support Laravel 4, I just installed it. The instructions are listed here. The steps are the following:

  1. Add "loic-sharma/profiler": "1.1.*" in the require section in composer.json
  2. Perform self-update => php composer.phar self-update in the console.
  3. Perform composer update => php composer.phar update loic-sharma/profiler in the console as well `
  4. Add 'Profiler\ProfilerServiceProvider', in the provider array in app.php
  5. Add 'Profiler' => 'Profiler\Facades\Profiler', in the aliasses array in app.php as well
  6. Run php artisan config:publish loic-sharma/profiler in the console

If you are using Laravel 5 you need to insert this before query or on middleware :

\DB::enableQueryLog();

For Eloquent you can just do:

$result->getQuery()->toSql();

But you need to remove the "->get()" part from your query.


Event::listen('illuminate.query', function($sql, $param)
{
    \Log::info($sql . ", with[" . join(',', $param) ."]<br>\n");
});

put it in global.php it will log your sql query.


Since the profiler is not yet out in Laravel 4, I've created this helper function to see the SQL being generated:


    public static function q($all = true) 
    {
        $queries = DB::getQueryLog();

        if($all == false) {
            $last_query = end($queries);
            return $last_query;
        }

        return $queries;
    }

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:

dd(DBH::q()); 

Here is the output I get: enter image description here

In case you are wondering, I use Kint for the dd() formatting. http://raveren.github.io/kint/


Last query print

$queries = \DB::getQueryLog();
$last_query = end($queries);

// Add binding to query
foreach ($last_query['bindings'] as $val) {
        $last_query['query'] = preg_replace('/\?/', "'{$val}'", $last_query['query'], 1);
}
dd($last_query);

Laravel 3

Another way to do this is:

#config/database.php

'profiler' => true

For all Queries result:

print_r(DB::profiler());

For last Result:

print_r(DB::last_query());

In Laravel 8.x you can listen to the event by registering your query listener in a service provider as documented in laravel.com website.

//header
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot()
{
   
  DB::listen(function ($query) {            
   Log::debug("SQL : " . $query->sql);
  });

}

You can then see all the queries in the laravel.log file inside storage\logs\laravel.log


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.

<script type="text/javascript">
    var queries = {{ json_encode(DB::getQueryLog()) }};
    console.log('/****************************** Database Queries ******************************/');
    console.log(' ');
    queries.forEach(function(query) {
        console.log('   ' + query.time + ' | ' + query.query + ' | ' + query.bindings[0]);
    });
    console.log(' ');
    console.log('/****************************** End Queries ***********************************/');
</script>

You can enable the "Profiler" in Laravel 3 by setting

'profiler' => true,

In your application/config/application.php and application/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.

enter image description here


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to orm

How to select specific columns in laravel eloquent Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] How to query between two dates using Laravel and Eloquent? Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? How to Make Laravel Eloquent "IN" Query? How to auto generate migrations with Sequelize CLI from Sequelize models? How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session Select the first 10 rows - Laravel Eloquent How to make join queries using Sequelize on Node.js What is Persistence Context?

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()

Examples related to laravel-query-builder

Get Specific Columns Using “With()” Function in Laravel Eloquent How to Create Multiple Where Clause Query Using Laravel Eloquent? Creating and Update Laravel Eloquent How Do I Get the Query Builder to Output Its Raw SQL Query as a String? How to Use Order By for Multiple Columns in Laravel 4? Laravel 4 Eloquent Query Using WHERE with OR AND OR? A JOIN With Additional Conditions Using Query Builder or Eloquent Get the Query Executed in Laravel 3/4