Я пытался записывать каждый SQL-запрос для laravel 5.2, поэтому я нашел много решений и попробовал приведенный ниже код, но почему-то это не сработало и не сгенерировало журнал.
В моем routes.php — Код не работает
Event::listen('illuminate.query', function($query, $bindings, $time, $name) {
dd("here");
$data = compact('bindings', 'time', 'name');
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else if (is_string($binding)) {
$bindings[$i] = "'$binding'";
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
echo $query;
Log::info('illuminate.query:'. $query);
});
Но я попробовал с другим примером кода, и он работает нормально
код в моем rout.php — работает нормально
DB::enableQueryLog();
DB::listen(
function ($sql) {
// $sql is an object with the properties:
// sql: The query
// bindings: the sql query variables
// time: The execution time for the query
// connectionName: The name of the connection
// To save the executed queries to file:
// Process the sql and the bindings:
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->bindings);
// Save the query to file
$logFile = fopen(
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
'a+'
);
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
fclose($logFile);
}
);
Мой вопрос : Зачем Событие :: слушать ( ‘illuminate.query’ не работает? Что-то я делаю не так?
Laravel не стрельба события, как illuminate.query
больше. Это было изменено на классы. https://github.com/laravel/framework/commit/41599959d45016f0280d986f758d414fbee81863
Теперь вам нужно поймать Illuminate\Database\Events\QueryExecuted
событие, если вы хотите, чтобы войти SQL запросов.
Вы должны определить своих слушателей в EventServiceProvider.php
вот так:
protected $listen = [
'Illuminate\Database\Events\QueryExecuted' =>[
'App\Listeners\YourListener'
],
]
Добавление этого в качестве ответа для @Hardy Mathew вместо комментария, поскольку комментарии не могут иметь форматирование кода:
Пример слушателя по запросу:
<?php
namespace App\Listeners;
use Illuminate\Database\Events\QueryExecuted;
class QueryExecutedListener
{
public function handle(QueryExecuted $event)
{
dd($event);
}
}
Обязательно добавьте слушателя в EventServiceProvider
как сказал @Giedrius Kiršys