0

I'm trying to attach executed sql queries to my request. Unforunately my $logs array is empty.

$logs = [];

\DB::listen(function ($query) use ($logs) {
   print_r($query->sql); // print_r here works
   $logs[] = $query;
});
print_r($logs); // here $logs is empty

Why my $logs array is empty, but inside DB::listen print_r() works? How can I fix it to get my queries in $logs array?

nextest
  • 35
  • 5
  • 1
    You could try and use `&$logs` instead of `$logs` in the parentheses after `use`. This way the variable is passed as reference instead of a local copy. – Philip Oct 28 '18 at 00:49
  • It doesn't work, array is still empty. – nextest Oct 28 '18 at 00:55
  • And when using `global $logs;` inside the function and removing the `use (..)`? Also what does `print_r()` give for just the `$query` variable? Maybe it should be `$logs[] = $query->sql;` ? – Philip Oct 28 '18 at 00:58
  • Still empty. Even with global inside and $logs[] = $query->sql – nextest Oct 28 '18 at 01:03
  • Can you give some more context of where these lines are in the code? – Philip Oct 28 '18 at 01:09
  • I'm testing this code in boot() method of AppServiceProvider, but I also tried in middleware in handle($request, Closure $next) method. In both places result is the same - empty array. – nextest Oct 28 '18 at 01:13
  • I'm assuming these lines are all next to each other, so in the same scope? – Philip Oct 28 '18 at 01:15
  • Yes, so there is no option to override $logs. Actually you can do the same in middleware or AppServiceProvider -> the result will be the same. – nextest Oct 28 '18 at 01:19

1 Answers1

0

The problem is there's a difference in time of execution between the code executed inside the ::listen() method and the lines before and after.

The code inside will be executed when a query is sent, while the other code is performed on startup of your app. Thus, after binding the function to the Database facade, no query is executed yet and $logs will be empty.

For logging

You could try and let the DB listener write the queries to a file or have a look at this post: https://stackoverflow.com/a/27753889/2142071

For adding to request

Inside the listen method use request()->request->add(['sql', $query->sql]); to have the sql variable available in the request object.

Philip
  • 2,888
  • 2
  • 24
  • 36
  • I don't want to log them to file. I want to attach all sql queries to request. How can I do that then? – nextest Oct 28 '18 at 01:26
  • You might be able to get the current request with the Request facade and then use `$request->request->add(['variable', 'value']);` to add the sql as a request variable or do the same but then with the Response facade (since that is what you're sending back to the browser). – Philip Oct 28 '18 at 01:32