Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Lumen provide a code for validation errors

Currently in lumen when you use the $this->validate($request, $rules) function inside of a controller it will throw a ValidationException with error for your validation rules(if any fail of course).

However, I need to have a code for every validation rule. We can set custom messages for rules, but I need to add a unique code.

I know there's a "formatErrorsUsing" function, where you can pass a formatter. But the data returned by the passed argument to it, has already dropped the names of the rules that failed, and replaced them with their messages. I of course don't want to string check the message to determine the code that should go there.

I considered setting the message of all rules to be "CODE|This is the message" and parsing out the code, but this feels like a very hacked solution. There has to be a cleaner way right?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I've solved this for now with the following solution:

private function ruleToCode($rule) {
    $map = [
        'Required' => 1001,
    ];

    if(isset($map[$rule])) {
        return $map[$rule];
    }

    return $rule;
}

public function formatValidationErrors(Validator $validator) {
    $errors = [];

    foreach($validator->failed() as $field => $failed) {
        foreach($failed as $rule => $params) {
            $errors[] = [
                'code' => $this->ruleToCode($rule),
                'field' => $field,
            ];
        }
    }

    return $errors;
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!