How to check if an array has an attribute?

1

I'm using Laravel 5.4 in an application, and a validator method gets an array .

This 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 does not come with these attributes it returns Undefined index .

Obs. I know I can create a new method and validate them separately, however I want to use only one method.

Validation function:

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);
}
    
asked by anonymous 16.02.2017 / 16:08

1 answer

2

After chat conversation, it was verified that the case was to oblige the user to have the phone if the DDD was informed.

To do this, you can use the validation rule required_with that makes that a field becomes mandatory if anyone informed in the rule is present.

As in the example using the question author's own code:

$regras = [
    'nome' => 'required',
    'ddd' => 'required_with:fone|min:2|max:2',
    'fone' => 'required_with:ddd|min:8|max:9'
];

What is being verified now?

name is still required, but phone just goes away   be obligatory if ddd is informed and vice versa .

In response to the question title, to check for an index within an array, you can use the PHP method array_key_exists :

If the index exists, it returns TRUE

$valores = [
    'nome' => $request->nome,
    'ddd'  => $request->ddd,
    'fone' => $request->fone
]

echo array_key_exists('ddd', $valores) // True

Otherwise, FALSE

$valores = [
    'nome' => $request->nome,
]

echo array_key_exists('ddd', $valores) // False
    
16.02.2017 / 16:28