Created
April 4, 2025 01:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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