vincent15000's avatar

Write a form to obtain the structure for sync with pivot values

Hello,

I'd like to obtain this structure.

'payments' => [
	2 => [
		'amount' => 85,
	],
	5 => [
		'amount' => 10,
	],
]

I have this code for the form.

<div class="flex flex-col gap-4">
    @foreach ($payments as $index => $payment)
        <div class="flex items-center">
            <input type="hidden" name="payments[{{ $index }}][amount]" value="{{ $payment['amount'] }}">

            <x-form.select name="payments[{{ $index }}]" id="{{ 'payment-'.$index }}">
                <option :value="null">Choisir un mode de paiement</option>

                @foreach ($paymodes as $item)
                    <option value="{{ $item->id }}" @selected($item->id == old('paymodes.'.$index, $payment['paymode_id']))>{{ $item->name }}</option>
                @endforeach
            </x-form.select>

            <div wire:click="addPayment()">ADD</div>
        </div>
    @endforeach
</div>

This line is not good.

 <x-form.select name="payments[{{ $index }}]" id="{{ 'payment-'.$index }}">

I have tested with <x-form.select name="payments[{{ $index }}][paymode_id]" id="{{ 'payment-'.$index }}">, but it gives me the paymode_id key just after the amount key.

Can you help me correct it ?

Thanks.

V

0 likes
5 replies
Tray2's avatar
Tray2
Best Answer
Level 73

When you define a name that can be multiple items, you use name="element_name[], I don't think you can even specify an index

1 like
vincent15000's avatar

@Tray2 It works when I specify an index.

I have decided to add [paymode_id] in the select name and then I map the array with the paymode_id key to handle the data and save them to the database.

vincent15000's avatar

@Tray2

I get this.

'payments' => [
	0 => [
		'amount' => 85,
		'paymode_id' => 2,
	],
	1 => [
		'amount' => 85,
		'paymode_id' => 5,
	],
]

And I handle the datas like this.

$payments = Arr::mapWithKeys($request->validated()['payments'], function (array $payment, int $key) {
    return [
        $payment['paymode_id'] => [
            'slug' => Str::ulid(),
            'amount' => $payment['amount'],
            'user_id' => auth()->id(),
        ],
    ];
});
vincent15000's avatar

@Tray2 It's exactly what I want, but I tried to obtain directly this structure from the form.

'payments' => [
	2 => [
		'amount' => 85,
	],
	5 => [
		'amount' => 10,
	],
]

And it seems to be impossible.

Please or to participate in this conversation.