Skip to content

Instantly share code, notes, and snippets.

@coreymcmahon
Created April 4, 2025 01:39
Show Gist options
  • Save coreymcmahon/8504b1d3d66db917c97a19be903e01de to your computer and use it in GitHub Desktop.
Save coreymcmahon/8504b1d3d66db917c97a19be903e01de to your computer and use it in GitHub Desktop.
Detect database queries in a Laravel app, throwing an exception if any detected
<?php
function detectDatabaseQueries(callable $callback)
{
DB::enableQueryLog();
$initialQueryCount = count(DB::getQueryLog());
$result = $callback();
$newQueryCount = count(DB::getQueryLog()) - $initialQueryCount;
if ($newQueryCount > 0) {
throw new \Exception('Database query detected in restricted block!');
}
return $result;
}
// Usage
detectDatabaseQueries(function() {
// Your code block here
// If any database query occurs, an exception will be thrown
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment