2
votes

Using Laravel 5.8 and generated field names, I would like to know if it is possible to change the validation messages used programmatically.

At the moment I am using the automatic redirection method of validating in my controller:

function processRequest(Request $request)
{
    $generated = session()->get('expected_field');
    $request->validate([
        'preset' => 'required',
        $generated => 'required'
    ]);
}

This works as expected, but the default error message results in

"The {$generated} field is required" and that's not useful.

I would like to do this without refactoring to a custom Request class.

1
with {$generated} you mean the value of that field right? for example "The mickey_mouse field is required" - IlGala
Yes, It can be anything (it's a random field, basically) - Darryl E. Clarke

1 Answers

5
votes

Checkout the "Custom Validation Attributes" in resoures/lang/{lang}/validation.php:

/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/

'attributes' => [],

Here, can set your own display values for various validation fields.

For example, if session()->get('expected_field'); was "first_name", but you wanted it to say "First Name", you'd set:

'attributes' => [
  'first_name' => 'First Name',
  ...
]

in that array and you'd be golden. The validation message would display as:

The First Name field is required.

You can also update the default message for each rule, in the "Validation Language Lines" section if you don't like the structure/wording of it.

-Edit-

validate() accepts a 2nd parameter, which is an array of validation messages. This can be customized to manipulate the string returned by session()->get('expected_field');, or omit it entirely in favour of a more generic error message:

$this->validate([
  $generated => 'required'
], [
  // $generated.'.required' => 'The '.ucwords(str_replace('_', ' ', $generated)).' field is required.'
  $generated.'.required' => 'The Anti-Spam field is required.'
]);

With this logic, the validation rule would trigger for whatever $generated is, but the message would be more generic, or a manipulation of $generated