0
votes

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.

1
What is the error are you getting?? Add that error in the question will be helpful for someone to answer the question. - Senthur
@Senthur there is no error. I am trying to figure out how to go about adding functionality to a Laravel method - sirhB
you can provide custom messages inside for loop - bhucho

1 Answers

1
votes

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();
        }