Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Validation Error Logger Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require foxen/laravel-validation-error-logger
    
  2. Publish Config

    php artisan vendor:publish --provider="Foxen\LaravelValidationErrorLogger\ServiceProvider"
    
    • Review config/validation-error-logger.php for default settings (e.g., log_channel and excluded fields).
  3. 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
        }
    }
    

Implementation Patterns

Core Workflow

  1. Automatic Logging

    • Attach the LogsValidationErrors trait to any class handling validation (controllers, form requests, etc.).
    • No manual logging required—errors are captured automatically when Validator::fail() is triggered.
  2. Customizing Logged Data

    • Override the getValidationErrorLoggerData() method to include/exclude fields dynamically:
      protected function getValidationErrorLoggerData()
      {
          return [
              'user_id' => auth()->id(),
              'ip' => request()->ip(),
              'errors' => $this->validationErrors(),
          ];
      }
      
  3. Conditional Logging

    • Skip logging for specific requests by overriding shouldLogValidationErrors():
      protected function shouldLogValidationErrors()
      {
          return !app()->environment('local');
      }
      
  4. Integration with Form Requests

    • Use the trait in form requests for centralized validation error handling:
      class StoreUserRequest extends FormRequest
      {
          use LogsValidationErrors;
      
          public function rules()
          {
              return ['email' => 'required|email'];
          }
      }
      
  5. Logging Custom Validation Messages

    • Extend the 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']})";
          }
      }
      
    • Bind the custom logger in AppServiceProvider:
      ValidationErrorLogger::swap(new CustomValidationErrorLogger());
      

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Logging validation errors adds minor overhead. Avoid using in high-frequency, low-risk validations (e.g., API rate limiting).
    • Mitigation: Use shouldLogValidationErrors() to disable logging for non-critical paths.
  2. Sensitive Data Exposure

    • Default logging includes all failed fields. Exclude sensitive data (e.g., passwords) in config/validation-error-logger.php:
      'exclude_fields' => ['password', 'password_confirmation', 'credit_card'],
      
    • Tip: Override getValidationErrorLoggerData() to filter fields dynamically.
  3. Channel Misconfiguration

    • If logs disappear, verify:
      • The log_channel in config/validation-error-logger.php matches a channel in config/logging.php.
      • The channel is properly configured (e.g., stack requires channels to be defined).
  4. Race Conditions in Multi-Threaded Environments

    • The package assumes single-threaded Laravel requests. In queue workers or parallel jobs, ensure logging is thread-safe.
  5. Overriding Without Parent Calls

    • If extending getValidationErrorLoggerData(), call parent::getValidationErrorLoggerData() to retain default behavior:
      return array_merge(parent::getValidationErrorLoggerData(), ['custom_field' => 'value']);
      

Debugging Tips

  1. Check Logs

    • Validate logs appear in the configured channel (e.g., storage/logs/laravel.log for single channel).
  2. Test Logging Manually

    • Force a validation failure in a test route:
      Route::get('/test-validation', function () {
          $validator = Validator::make([], ['required' => 'invalid']);
          if ($validator->fails()) {
              // Logs automatically via trait
          }
      });
      
  3. Inspect the Trait

    • The trait hooks into Laravel’s 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.
  4. Clear Cache

    • After publishing config or extending the package, run:
      php artisan config:clear
      php artisan cache:clear
      

Extension Points

  1. Custom Loggers

    • Implement Foxen\LaravelValidationErrorLogger\Contracts\ValidationErrorLogger to create domain-specific loggers (e.g., database storage).
  2. Event-Based Logging

    • Listen to validation.failed events for async processing:
      Event::listen(ValidationFailed::class, function ($event) {
          // Custom logic here
      });
      
  3. Dynamic Channel Selection

    • Override getLogChannel() to route errors to different channels based on context:
      protected function getLogChannel()
      {
          return request()->is('admin/*') ? 'admin' : config('validation-error-logger.log_channel');
      }
      
  4. Slack/Email Alerts

    • Extend the logger to notify teams via 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));
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager