Let's say we have a helper function, logDatabaseError($exception) that logs QueryExceptions to a special log.
helpers.php
function logDatabaseError ($exception) {
$controller = ????;
$function = ????;
$log_string = "TIME: ".now().PHP_EOL;
$log_string.= "User ID: ".Auth::user()->id.PHP_EOL;
$log_string.= "Controller->Action:".$controller."->".$function.PHP_EOL;
$log_string.= $exception.PHP_EOL;
Storage::disk('logs')->append('database.log', $log_string);
}
This function is called from multiple controllers and multiple functions within those controllers.
Whenever something needs to be written to the database, in the catch part, we call this logDatabaseError function and pass to it the \Illuminate\Database\QueryException as $exception.
BestControllerEverController.php
class BestControllerEver extends Controller
{
function writeStuffToDatabase (Request $request) {
try {
DB::does-its-thing
}
catch(\Illuminate\Database\QueryException $exception) {
logDatabaseError($exception)
}
}
}
Is it possible for the logDatabaseError function to get both Controller name and function name without passing them as function parameters?
In this particular example case, $controller and $function variables in logDatabaseError function would be set to BestControllerEver and writeStuffToDatabase, respectively.
I know this is logged in the stack trace, but their location in $exception object is not always the same and extracting it from there is not reliable, at least from my limited experience.