GaspardP
GaspardP

Reputation: 890

Creating an array of objects in a Laravel form

I'd like to create an array of objects (or a bi-dimensional array) from a form using Laravel

the blade.php looks like

@foreach($objets as $objet)
<tr>
    <td>
        <input type="text" name="objets[]" id="field_A" value="{{$objet->field_A}}">
    </td>
    <td>
        <input type="text" name="objets[]" id="field_B" value="{{$objet->field_B}}">
    </td>
</tr>
@endforeach

Currently, when validating the form, the variable $objets is an array, with all values, but not an array of array.

Upvotes: 0

Views: 841

Answers (1)

Jelly Bean
Jelly Bean

Reputation: 1219

Update your input names as follows:

<td>
  <input type="text" name="objets[][fieldA]" id="field_A" value="{{$objet->field_B}}">
</td>
<td>
  <input type="text" name="objets[][fieldB]" id="field_B" value="{{$objet->field_B}}">
</td>

The above will output an array with array

"objects" => array:1 [▼
                0 => array:7 [▼
                   'fieldA' => 'value'
                   'fieldB' => 'value'
                ]
             ]

Then in your validation you can use it like this:

$validate['objects.*.field_A'] = 'required';
$validate['objects.*.field_B'] = 'required';
return $validate;

Upvotes: 1

Related Questions