Wikke
Wikke

Reputation: 41

Proper way to write a dynamically built PHP form with input from array in Laravel

So I'm pretty new to Laravel and not at the point where I have mental bandwidth to mess with Vue. In the meantime, I'm also trying to build forms dynamically to make the code easier on the eyes.

My code looks like this:

<form action='{{ route('agents.store') }}' method='POST'>
        @csrf

        @php
            $details = ['prop' => 'labelName', ...];
        @endphp

        @foreach ($details as $data => $label)
            <div class="{{ $data }}">
                <label for="{{ $data }}">
                    {{ $label }}:
                </label>
                <input type="text" name="{{ $data }}" id="{{ $data }}" value="{{ old('{{$data}}') }}">
                @error('{{ $data }}')
                    {{ $message }}
                @enderror
            </div>
        @endforeach

Now, this seems to work fine. I do, however, get an error when I save this and the formatting option of VSC refuses. I assume this is because value="{{ old('{{$data}}') }}"

is basically doubling down on inserting a variable dynamically.

Is there a proper way I can build my form in the meantime (before learning probably Vuejs)? This form takes 15 inputs and it gets pretty messy.

Kind regards in advance.

I've tried old, trusty SO & Google. Amongst other, I found this solid post but trying different apostrophes and ticks just led to variations of error message

Parse Error : syntax error, expecting ')' on line 1 > 1 | | ^

There are apostrophes needed for the old(''), so I've added extra and different types in the old() and the array, but I keep getting slight variations on the same error.

Upvotes: 1

Views: 47

Answers (1)

Wikke
Wikke

Reputation: 41

I don't know if it's the proper way to close my question, but with @krisgjika's answer I'm all set...

Upvotes: 0

Related Questions