For an API using Laravel and MySQL we are trying to setup an audit mechanism using MySQL triggers.
We’ve extended IlluminateDatabaseDatabaseManager
with something like
public function connection($name = null)
{
$conn = parent::connection($name);
$conn->statement("SET @app_user_id=?", [Auth::user()->id ?? 'no_login']);
return $conn;
}
Then inside the BEFORE UPDATE
trigger we get @app_user_id
and set the updated_by
. This seems to be working well, is there a better way to do this, we don’t want to use eloquent model events and we are fine using MySQL triggers, what possible issues we may face? Example:
- When multiple users are using the application at the same time is it possible that we face race conditions, say due to connection pool reuse, and same
@app_user_id
is used among requests by different users? - We noticed
DatabaseManager->connection()
is called a lot and also there may be cases we don’t want to set the@app_user_id
at all, example when doing a mass update through a command. Could we set the@app_user_id
inside a middleware, maybe extendingIlluminateAuthMiddlewareAuthenticate
without loosing something? Is it possible the DB update that happens later will use a different connection that doesn’t have@app_user_id
set ?
Thanks in advance and please let me know if more explanation is needed.
1