SoFunction
Updated on 2025-04-04

Laravel framework implements the function of using listeners to record SQL statements

This article describes the Laravel framework implementing the SQL statement record function using listeners. Share it for your reference, as follows:

Use listeners to record SQL statements

1. The event class that listens to SQL statements has been defined, just create the listener class:

# Listen to SQLmake:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted

2. Listener class code

./app/Listeners/

<?php
namespace App\Listeners;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Http\Models\OperationLog;
class QueryListener
{
  /**
   * Create the event listener.
   *
   * @return void
   */
  public function __construct()
  {
    //
  }
  /**
   * Handle the event.
   *
   * @param QueryExecuted $event
   * @return void
   */
  public function handle(QueryExecuted $event)
  {
    $sql = str_replace("?", "'%s'", $event->sql);
    $log = vsprintf($sql, $event->bindings);
    # Here the $uid definition depends on middleware to record operation log code    $uid = isset($_SERVER['admin_uid']) ? $_SERVER['admin_uid'] : 0;
    if('select' != substr($log , 0 , 6)){
      if('insert into `operationLog`' != substr($log , 0 , 26)){
        $OperationLog = new OperationLog();
        $OperationLog->uid = $uid;
        $OperationLog->sql = $log;
        $OperationLog->input = '';
        $OperationLog->save();
      }
    }
  }
}

3. Introduce a listener

./app/Providers/

protected $listen = [
    ...
    \Illuminate\Database\Events\QueryExecuted::class => [
      'App\Listeners\QueryListener'
    ],
    ...
  ];

At this time, the SQL log will be recorded when performing operations