randm's avatar

Is there an easy way to find out where are my queries are being generated from?

Hi, I am building an application using Laravel 5.1. I am trying I use Eloquent as an ORM to interact with my database.

One of the things that I am having difficulties with is trying to identify the source of each query being generated my Eloquent.

Trying I understand what is being executed at the server, I turn on MySQL general log and log it to a table "for easy access." However, I got 36 queries being exexuted from a single page refresh "this is a red flag in my mind."

The challenge here is how to know what job/what at what point in my code was each query generated?

I want to make sure I don't sacrafy DB performance because I am trying to use Eloquent.

How can I drill down the source of each query?

Does Eliquent have its own log? If so where do I find it? If not how would I know what is generating these queries?

It would be very nice if Eloquent have its own general logs like MySQL. I would be a dream come true if the eloquent log would tell me at what point in my code query x was executed. To take this thought further, it will be yet more powerful if the queries are logged in a general format where one can get stats on how many time query x was generated regardless of the vales passes to it. It will help to know if query x was cached by the application or not.

Thank you for your help.

0 likes
10 replies
bobbybouwmann's avatar

Like said above, the laravel-debugbar is really usefull in this case!

mstnorris's avatar

Along with the above packages, I sometimes prefer a more direct way that listens for SQL queries and dumps them right alongside your code; put the following in your routes.php file and that's all you need.

Event::listen('illuminate.query', function($sql) {
    var_dump($sql);
});

This way you can not only see what query is being executed, but where it is being executed. It is great in finding N+1 issues when iterating through lists.

1 like
randm's avatar

@mstnorris is there a way to add a listener to show the query after it is prepared? Instead of looking at ? ? ? ? I like to evaluate the number that are being passed

thomaskim's avatar

@mstnorris @malhayek You can accept 3 more parameters. :)

Event::listen('illuminate.query', function($query, $bindings, $time, $name)
{
    var_dump($query);       // The query
    var_dump($bindings);    // The arguments being passed to the query
    var_dump($time);        // The amount of time the query took to run
    var_dump($name);        // The database connection name
});
bobbybouwmann's avatar

You can also do this

User::where('username', '=', $name)->orWhere('active', '=', 1)->toSql();

You can perform the toSql function instead of get or first

Please or to participate in this conversation.