2

I am trying to make an ajax based form for laravel, but im using the laravel validation method to check the input.

The validation errors return a basic list of errors, but I need the specific input name used as a key for each item in the array. I will need this so I can add the message next to the input via javascript.

I have looked at the documentation but cant seem to find anything that will do this. I want to avoid checking each input for errors individually so i can reuse the code on other forms.

Have I missed something here, any ideas on how I can achieve this?

PHP

$rules = ['username' => 'required', 'password' => 'required'];
$validator = Validator::make(Request::input(), $rules);

if($validator->fails())
{
    $data = $validator->errors()->all();
}

RESULT:

$data = [
    0 => 'The username field is required.',
    1 => 'The password field is required.'
]

DESIRED RESULT:

$data = [
    'username' => 'The username field is required.',
    'password' => 'The password field is required.'
]

2 Answers 2

5

Instead of $validator->errors()->all() use $validator->errors()->messages() to get the errors keyed by their input names:

$data = [
    'username' => [
        0 => "The username field is required."
    ],
    'password' => [
        0 => "The password field is required."
    ],
 ];
Sign up to request clarification or add additional context in comments.

Comments

0

I think you make mistake there.

$data = ['validation' => $validator->errors()->all()];

Try this

$rules = ['username' => 'required', 'password' => 'required'];
$validator = Validator::make(Request::input(), $rules); 
if($validator->fails()) { 
$data = $validator->errors()->all(); 
}

1 Comment

I did thank you, but this doesn't help me solve the issue of the array not containing messages with input names as keys.

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.