Manual validation of an array in Laravel 5.6

0

I have a form where the telefone field is created dynamically, since a cliente can have several registered phones, being in the following pattern:

<input type="text" name="clientes[nome]">
<input type="tel" name="telefones[0][numero]">
<input type="tel" name="telefones[1][numero]">
<input type="tel" name="telefones[2][numero]">
...

And I have a ClientesRequest class that extends the FormRequest class with the following rules:

public function rules()
{
    return [
        'clientes.nome' => 'required',
        'telefones.*.numero' => 'required'
    ];
}

public function messages()
{
    $messages = [
        'clientes.nome.required' => 'O nome é obrigatório!',
    ];

    if($this->request->get('telefones')) {
        foreach ($this->request->get('telefones') as $key => $val) {
            $messages['telefones.' . $key . '.numero.required'] = 'Preencha o número do telefone '. ($key + 1) .'!';
        }
    }

    return $messages;
}

It works normally and validates all phones.

However, there was a need to manually validate fields using the Validator::make() method.

If I put the snippet below, it usually works for the nome field and the O nome é obrigatório! message is displayed on the screen:

$cliente = '';
$validator = new ClientesRequest();
$validate = \Validator::make(['clientes' => ['nome' => $cliente]], [$validador->rules()['clientes.nome']], $validador->messages());

However, if I try to validate the phone, it falls into the correct rule, but does not return the custom message I set in the ClientesRequest class, because when calling the Validator::make method, there is no request to satisfy the condition that leads to foreach that defines a message for each input of phone.

The return I have is only: validation.required

I'm trying to do that for the phone (hardcode for example):

$telefone= '';
$validator = new ClientesRequest();
$validate = \Validator::make(['telefones' => [['numero' => $telefone]], ['telefones.0.numero' => $validador->rules()['telefones.*.numero']], $validador->messages());

Is there any way to display the custom message I set in the ClientesRequest class, using the Validator::make method?

    
asked by anonymous 25.05.2018 / 16:41

0 answers