0

I'm saving data that pass my validation. The validation is setted in a array called $rules:

$rules = array(
        'name_field' => 'required|unique:users',
        'number_in_db' => 'required',
    );
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
    MyModel::create($request->input());

    return redirect()->route('some.route')->withFlashSuccess('Done!');
    } else
    return redirect()->back()->withInput()->withErrors($validator);

Works fine, but when it redirects to the view with the errors, it is showing me the field names exactly as the array, for example: "The name_field is already registered". How can I declare a custom name for every field? and for example have something like "The Name is already registered".

1 Answer 1

2

From Laravel Doc..

  1. Custom Error Messages

You may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$messages = [
    'name.required' => 'The "name" field is required!',
    'name.unique'   => 'The "name" field is should be unique!',
];

$validator = Validator::make($input, $rules, $messages);
  1. Specifying Custom Attributes In Language Files

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom name in the attributes array of your resources/lang/xx/validation.php language file:

'attributes' => [
    'name_field'   => 'name',
    'number_in_db' => 'number',
],

There are some more options available in the official doc. But I would suggest you to go with the "Specifying Custom Attributes In Language Files" method.

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.