Skip to content

Instantly share code, notes, and snippets.

@ilterocal
Last active March 18, 2016 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilterocal/b4562380ae2b265bc591 to your computer and use it in GitHub Desktop.
Save ilterocal/b4562380ae2b265bc591 to your computer and use it in GitHub Desktop.
Logging Laravel 5 SQL Queries in Controller.
<?php namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class QueryLoggingController extends Controller
{
public function __construct()
{
DB::listen(
function ($sql, $bindings, $time) {
// To save the executed queries to file:
// Process the sql and the bindings:
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'), $sql);
$query = vsprintf($query, $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);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment