pmiranda
pmiranda

Reputation: 8420

Laravel, catch the error after Validation

Laravel 5.1 I have this code:

$validator = Validator::make($request->all(), [
    'name' => 'required|max:255',
    'file' => 'required|max:2000',
]);
if ($validator->fails()) {
    // do something depending the error before returning and redirect
    if (name not present) {
      my code for this
    }

    if (file larger than 2000) {
      my code for this
    }

    return redirect()
    ->back()
    ->withErrors($validator)
    ->withInput();
}

So, if the name is not present, I need to run some code, and if the file is larger than 2000, another one and so on.

How can I catch which rule did fail?

Upvotes: 1

Views: 59

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

Pretty simple actually. In the same way that $errors is globally passed to the frontend, and has the method has(), you can check the error in the Controller before redirecting:

$validator = Validator::make($request->all(), [
  'name' => 'required|max:255',
  'file' => 'required|max:2000',
]);
if ($validator->fails()) {
  // do something depending the error before returning and redirect
  if($validator->errors()->has('name')){
    // Do whatever for `name` issue.
  }

  if($validator->errors()->has('file')){
    // Do whatever for `file` issue.
  }

  return back()
  ->withErrors($validator)
  ->withInput(); // Don't need `redirect()->back()`, `back()` is enough.
}

Note, this will catch both the required and max rules. To check individual rules, you can use the failed() method in conjunction with isset():

if ($validator->fails()) {
  $failedValidation = $validator->failed();
  if(isset($failedValidation['name']['Max'])){
    ...
  }

  if(isset($failedValidation['file']['Max'])){
    ...
  }
  ...
}

Upvotes: 3

Related Questions