Laravel - validate input arrays and return values in case of error

3

I am creating form using the following code:

In the create.blade.php file

{!! Form::open(['route'=>'orcamentos.store']) !!}
{!! Form::text('descricao', null, ['class'=>'form-control', 'autofocus']) !!}
{!! Form::text('produto[]', null, ['class'=>'form-control']) !!}
{!! Form::text('produto[]', null, ['class'=>'form-control']) !!}
// Esse campo produto pode se repetir inúmeras vezes em tela
{!! Form::submit('Salvar', ['class'=>'btn btn-primary']) !!}

Notice that I can have 'N' input 'product'.

In my controller I have this:

public function store(OrcamentoRequest $request){...}

And in the OrcamentoRequest class I want to validate the mandatory fields, does anyone know how I can do this?

Within function rules I have already made some attempts based on the searches made on the internet, but I did not succeed.

Below are some unsuccessful attempts:

TRY 1:

$rules = [
     'descricao' => 'required',
     'produto.*' => 'required',
 ];

TRY 2:

foreach($this->request->get('produto') as $key => $val){
  $rules['produto.'.$key] = 'required';
} 

I also found something in the documentation itself. link here but nothing worked.

The error you are giving is this:

ErrorException in helpers.php line 531:
htmlentities() expects parameter 1 to be string, array given

Has anyone gone through this before? Or do you know the answer?

    
asked by anonymous 01.06.2016 / 04:09

1 answer

2

I've been testing and for what it seems to me to be doing it this way is because it's using Laravel 5.2, since the previous ones had no built-in validation for array inputs so I did:

LARAVEL 5.2:

HTML:

@foreach ($errors->all() as $error)
    {{$error}}<br>  <!-- imprimir os erros de validação caso haja algum, serão enviados pelo Validator -->
@endforeach

<form action="/product/store" method="POST">
    {!! csrf_field() !!}
    <input type="text" name="descricao" value="{{old('descricao')}}"></input>
    <input type="text" name="products[]" value="{{old('products.0')}}"></input>
    <input type="text" name="products[]" value="{{old('products.1')}}"></input>
    <input type="text" name="products[]" value="{{old('products.2')}}"></input>
    <input type="text" name="products[]" value="{{old('products.3')}}"></input>
    <input type="submit">
</form>

Routa:

Route::post('/product/store', 'TestsController@product_store');

Controller:

use Validator;
...

public function product_store(Request $request) {

    $inputs = $request->except('_token'); // valores de todos os inputs excepto o do csfr token
    // $inputs = Array ( [descricao] => mobilidade [products] => Array ( [0] => carro [1] => mota [2] => camiao [3] => barco) )

    $rules = array(
        'descricao' => 'required', // mesmo nome dos nossos inputs, name="descricao"
        'products.*' => 'required' // mesmo nome dos nossos inputs, name="products"
    );

    $validator = Validator::make($inputs, $rules);
    if($validator->fails()) {
        return redirect()->back()->withInput()->withErrors($validator); // voltar para trás e enviar os erros, regras ($rules), que não foram respeitadas
    }
    // Esta tudo bem, fazer outras coisas
}

And it worked.

LARAVEL 5.1:

Here I had to take a slightly different approach since it does not seem to have validation for arrays by default:

The only thing I changed was in the controller, so:

public function product_store(Request $request) {

    $inputs = $request->except('_token');
    // $inputs = Array ( [descricao] => mobilidade [products] => Array ( [0] => carro [1] => mota [2] => camiao [3] => barco) )

    $products = array(
        'descricao' => $inputs['descricao'], // valor da descricao introduzido
    );

    $rules = array(
        'descricao' => 'required', // mesma key que demos nos $products
    );

    foreach ($inputs['products'] as $key => $value) {
        $products['product_' .$key] = $value;
        $rules['product_' .$key] = 'required';
    }

    $validator = Validator::make($products, $rules);
    if($validator->fails()) {
        return redirect()->back()->withInput()->withErrors($validator); // voltar para trás e enviar os erros, regras ($rules), que não foram respeitadas
    }
    // Esta tudo bem, fazer outras coisas
}

Always remember that the keys of the rules, our $rules , must be the same keys of the array that we will validate, in the latter case of $products

    
01.06.2016 / 13:29