foxen/laravel-validation-error-logger
Log Laravel validation errors automatically from FormRequest classes using a simple trait. Configure the log channel and exclude sensitive fields (e.g., passwords) via a published config file, with per-request overrides available.
Installation
composer require foxen/laravel-validation-error-logger
Publish Config
php artisan vendor:publish --provider="Foxen\LaravelValidationErrorLogger\ServiceProvider"
config/validation-error-logger.php for default settings (e.g., log_channel and excluded fields).First Use Case
Use the LogsValidationErrors trait in a controller or form request:
use Foxen\LaravelValidationErrorLogger\Traits\LogsValidationErrors;
class UserController extends Controller
{
use LogsValidationErrors;
public function store(Request $request)
{
$validated = $request->validate([
'email' => 'required|email',
'password' => 'required|min:8',
]);
// Validation errors will auto-log if validation fails
}
}
Automatic Logging
LogsValidationErrors trait to any class handling validation (controllers, form requests, etc.).Validator::fail() is triggered.Customizing Logged Data
getValidationErrorLoggerData() method to include/exclude fields dynamically:
protected function getValidationErrorLoggerData()
{
return [
'user_id' => auth()->id(),
'ip' => request()->ip(),
'errors' => $this->validationErrors(),
];
}
Conditional Logging
shouldLogValidationErrors():
protected function shouldLogValidationErrors()
{
return !app()->environment('local');
}
Integration with Form Requests
class StoreUserRequest extends FormRequest
{
use LogsValidationErrors;
public function rules()
{
return ['email' => 'required|email'];
}
}
Logging Custom Validation Messages
ValidationErrorLogger class to format messages:
use Foxen\LaravelValidationErrorLogger\ValidationErrorLogger;
class CustomValidationErrorLogger extends ValidationErrorLogger
{
protected function formatError(array $error)
{
return "[{$error['field']}] {$error['message']} (Rule: {$error['rule']})";
}
}
AppServiceProvider:
ValidationErrorLogger::swap(new CustomValidationErrorLogger());
Performance Overhead
shouldLogValidationErrors() to disable logging for non-critical paths.Sensitive Data Exposure
config/validation-error-logger.php:
'exclude_fields' => ['password', 'password_confirmation', 'credit_card'],
getValidationErrorLoggerData() to filter fields dynamically.Channel Misconfiguration
log_channel in config/validation-error-logger.php matches a channel in config/logging.php.stack requires channels to be defined).Race Conditions in Multi-Threaded Environments
Overriding Without Parent Calls
getValidationErrorLoggerData(), call parent::getValidationErrorLoggerData() to retain default behavior:
return array_merge(parent::getValidationErrorLoggerData(), ['custom_field' => 'value']);
Check Logs
storage/logs/laravel.log for single channel).Test Logging Manually
Route::get('/test-validation', function () {
$validator = Validator::make([], ['required' => 'invalid']);
if ($validator->fails()) {
// Logs automatically via trait
}
});
Inspect the Trait
Validator facade. Debug by checking:
vendor/foxen/laravel-validation-error-logger/src/Traits/LogsValidationErrors.php for logic.app/Providers/AppServiceProvider.php for service binding overrides.Clear Cache
php artisan config:clear
php artisan cache:clear
Custom Loggers
Foxen\LaravelValidationErrorLogger\Contracts\ValidationErrorLogger to create domain-specific loggers (e.g., database storage).Event-Based Logging
validation.failed events for async processing:
Event::listen(ValidationFailed::class, function ($event) {
// Custom logic here
});
Dynamic Channel Selection
getLogChannel() to route errors to different channels based on context:
protected function getLogChannel()
{
return request()->is('admin/*') ? 'admin' : config('validation-error-logger.log_channel');
}
Slack/Email Alerts
Notification facade:
use Illuminate\Notifications\Notification;
class SlackValidationErrorLogger extends ValidationErrorLogger
{
protected function log(array $data)
{
Notification::route('slack', config('services.slack.webhook'))
->notify(new ValidationFailedNotification($data));
}
}
How can I help you explore Laravel packages today?