简体   繁体   中英

Laravel 5.5 validating hasMany relationship

How can I create a validation on a hasMany relationship

That is my Product model

public function produtoAtributos(){
    return $this->hasMany("App\ProdutoAtributo", "produto_id", 'id')->latest();
}

and in Controller I fill the inputs than save it

$produtoatributos = $model->produtoAtributos()->getModel();

$produtoatributos->tipo = $produtoAtributo['tipo'];

$model->produtoAtributos()->save($produtoatributos);

The form input looks like this

<input name="ProdutoAtributos[0]['tipo']" />

How can add a validation for the relationship?

Laravel provide a nice way to validate arrays inpputs.

Here is an example

$validator = Validator::make($request->all(), [
        'ProdutoAtributos.*.tipo' => 'required',
    ]);

You can read more about it here

https://laravel.com/docs/5.6/validation#validating-arrays

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM