1
I’m using Laravel 5.4 in an application, and a validator method receives a array.
That one array can have the attributes:
[
'nome' => $request->nome,
'ddd' => $request->ddd,
'fone' => $request->fone
]
Or just:
[
'nome' => $request->nome
]
How do I check if it comes with the attributes ddd
and fone
, since if it doesn’t come with these attributes it comes back Undefined index.
obs. I know I can create a new method and validate them separately, but I want to use only one method.
Function for validation:
private function validaComTelefone($data)
{
$regras = [
'nome' => 'required',
'ddd' => 'required|min:2|max:2',
'fone' => 'required|min:8|max:9'
];
$mensagens = [
'nome.required' => 'Campo nome é obrigatório',
'ddd.required' => 'Campo ddd é obrigatório',
'ddd.min' => 'Campo ddd deve ter 2 dígitos',
'ddd.max' => 'Campo ddd deve ter 2 dígitos',
'fone.required' => 'Campo telefone é obrigatório',
'fone.min' => 'Campo telefone deve ter ao menos 8 dígitos',
'fone.max' => 'Campo telefone deve ter no máximo 9 dígitos'
];
return Validator::make($data, $regras, $mensagens);
}
If you are putting "required", the indexes are mandatory, if they do not exist, the Validator passes the values to Messagebag, it should not be your validation that is cussing the
Undefined Index
, can you put the full log (line and sample number) or even the fragment that is using its function in the question? and to check if there is you can use thearray_key_exists
– Pliavi
is that if ddd then ddd and headset are required, I believe I will have to change my logic. So I need to know how to check if there is such an attribute in the array
– Felipe Paetzold
Ah, the Laravel has the right filters for this, like the
required_with
, I’ll give you an organized response.– Pliavi
@Pliavi solved with array_key_exists, I will put an answer with it, but I await your solution :)
– Felipe Paetzold