A
A
asdasdqwe2021-11-14 18:20:17
Laravel
asdasdqwe, 2021-11-14 18:20:17

How to make dynamic fields in laravel?

There is 1 field

<input name="hobby[]" >

<div>добавить хобби</div>

<button> </button>


When the button is clicked, add a field - input is copied (via javascript) and 2 hobby fields are obtained
<input name="hobby[]" >
<input name="hobby[]" >

<div>добавить хобби</div>

<button> </button>


Validation: Let's say we don't fill in the second field and it seems that we should get an error, laravel redirects back, but of course I don't see the error, because the second field is no longer there (it was copied by javascript) How to make the second field not removed after sending?
"hobby.*" => 'required|string',


Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-11-14
@delphinpro

The previous values ​​can be obtained by a function old()
in old('hobby')you will have an array.
Here, display all the fields

@foreach(old('hobby') as $value)
  <input name="hobby[]" value="{{ $value }}"
@endforech

Well, error output in the usual way
@if ($errors->any())
  @foreach ($errors->all() as $error)
    <p>{{ $error }}</p>
  @endforeach
@endif

Something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question