Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 269
SpaceDogCS Avatar asked Mar 15 '18 14:03

SpaceDogCS


1 Answers

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

like image 67
Romantic Dev Avatar answered Sep 19 '22 17:09

Romantic Dev