Blade components with array names not showing "old" values

Viewed 61

I'm new to Laravel and have run into a problem.

I have a single page which collects information about a Parent and a Child (two different models). To allow for separate validation, and because the models share some fields, I've created a form that uses parent[...] and child[...] arrays to keep the fields separate. In the controller, I can then validate and create parents, linked to children etc. The controller is working, the validation is working - validated data is being added to the database...

However, I'm running into problems with the validation errors.

I have the following (example) Blade component to display a textarea.

components/form/textarea.blade.php:

<x-form.field>
    <x-form.label name="{{ $name }}">{{ $slot }}</x-form.label>

    <textarea name="{{ $name }}"
             id="{{ $name }}"
    >{{ old($name) ?? $slot) }}</textarea>
    <x-form.error name="{{ $name }}"/>
</x-form.field>

This works find for components with plain names such as:

<x-form.textarea name="notes"/>

However, I'm running into problems when this is part of an array:

<x-form.textarea name="child[notes]"/>

In this instance the old values and any validation errors don't show. They do show when I hard-code the name to "dot" notation: child.notes.

Is there a method I can use to convert the name dynamically so that the form gets the correct array syntax and the old and @error get a dotted version thereof?

Or should I be using a different approach altogether?

Edit:

Using the example:

<x-form.textarea name="child[notes]">Child Notes</x-form.textarea>

I imagine that it would expand to the first level at least, as follows:

<x-form.field>
    <x-form.label name="child[notes]">Child Notes</x-form.label>

    <textarea name="child[notes]"
             id="child[notes]"
    >{{ old("child[notes]") ?? "") }}</textarea>
    <x-form.error name="child[notes]"/>
</x-form.field>

However, I want it to expand like this:

<x-form.field>
    <x-form.label name="child[notes]">Child Notes</x-form.label>

    <textarea name="child[notes]"
             id="child[notes]"
    >{{ old("child.notes") ?? "") }}</textarea>
    <x-form.error name="child.notes"/>
</x-form.field>
1 Answers
<x-form.textarea name="{{child['notes']}}"/>

Your array key should be inside double braces and quote the key string.

Related