I have a requirement that I need to save each and every query executed by the laravel program. I have created following listener in boot
method of app/Http/Providers/AppServiceProvider
public function boot()
{
DB::listen(
function ($query) {
$query_binding = '';
foreach ($query->bindings as $binding) {
$query_binding .= $binding . ', ';
}
QueryLog::create([
'sql' => $query->sql,
'bindings' => $query_binding,
'time' => $query->time
]);
}
);
}
I get following error:
SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'bindings' at row 1 (SQL: insert into query_log
(sql
, bindings
, time
, updated_at
, created_at
) values (insert into query_log
(sql
, bindings
, time
, updated_at
, created_at
) values (insert into query_log
(sql
, bindings
, time
, updated_at
, created_at
) values (0.17, 2018-03-26 07:27:36, 2018-03-26 07:27:36, ?, ?), insert into query_log
(sql
, bindings
, time
, updated_at
, created_at
) values (?, ?, ?, ?, ?), select * from users
where id
= ? limit 1, 3, , 2.63, 2018-03-26 07:27:36, 2018-03-26 07:27:36, , 0.23, 2018-03-26 07:27:36, 2018-03-26 07:27:36, , 0.17, 2018-03-26 07:27:36, 2018-03-26 07:27:36, , ?, ?, ?, ?), ?, ?, ?, ?))
I believe this is due to the DB::listen
listen to its own query and try to save it creates a infinite loop.
How to exclude the saving query of DB::listen
and save all the other queries?
The most easy part should be checking on the table and then escape it.
public function boot()
{
DB::listen(
function ($query) {
if (strpos($query->sql, 'querylogtable') !== false ) {
// we don't want to log about the logging
return;
}
QueryLog::create([
'sql' => $query->sql,
'bindings' => implode(', ', $query->bindings),
'time' => $query->time
]);
}
);
}
I have used implode and not a foreach to glue the bindings
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community