0

I am using Laravel's validator but I am having trouble figuring out how to modify the validator to display the index of the array which contains an error. My input rows are named as rows[indexNumberGoesHere][indexNameGoesHere].

As of now, I am going about the validation very simply:

$data = $request->validate([
   'rows.*.title' => 'required', 
   'rows.*.price' => 'required', 
   'rows.*.quantity' => 'required', 
   'rows.*.discount' => 'nullable', 
   'rows.*.description' => 'nullable', 
   'rows.*.taxable' => 'nullable', 
]);

How can I go about using Laravel's validator to display a custom message to tell the user which exactly field contains an error? As of now, if the first title is empty, it returns the error: The rows.0.title field is required.

I would like to be able to customize the error text to say something like Row 1: Please fill in the title field.

Thanks in advance.

3
  • What is the error are you getting?? Add that error in the question will be helpful for someone to answer the question. Commented Jan 24, 2021 at 3:20
  • @Senthur there is no error. I am trying to figure out how to go about adding functionality to a Laravel method Commented Jan 24, 2021 at 3:24
  • you can provide custom messages inside for loop Commented Jan 24, 2021 at 8:45

1 Answer 1

1

You can pass custom messages using the validator class. there are two ways first to use directly which I am showing below the second is to use form request class, you can add a messages function in there to have your message.

first import validator facade use Illuminate\Support\Facades\Validator;

$messages = [];
$rules = [
   'rows.*.title' => 'required', 
   'rows.*.price' => 'required', 
   'rows.*.quantity' => 'required', 
   'rows.*.discount' => 'nullable', 
   'rows.*.description' => 'nullable', 
   'rows.*.taxable' => 'nullable', 
];
foreach($request->get('rows') as $key => $val){
    $messages["rows.$key.*.required"] = "Row {$key+1}: Please fill in the :attribute field.";
    // Similarly for other fields ...
}

Then pass the validation with your custom messages.

$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
            return redirect()->back()
                        ->withErrors($validator)
                        ->withInput();
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.