Home > Back-end >  How to update dynamic input fields in Laravel?
How to update dynamic input fields in Laravel?

Time:11-27

This is the code for storing an array only. What I want now is to update each field or can add new rows but I don't know how.

        foreach ($request->requirements as $key => $requirements) {
        $req = new FormReq();
        $req->requirements = $requirements['title'];
        $req->form_id = $id;
        $req->save();
    }

My blade file

@foreach ($requirements as $reqs)
    <tr>
        <td><input type="text" name="requirements[0][title]"
            placeholder="Enter requirements" 
            value="{{ $reqs->requirements }}" />
        </td>
        <td><button type="button" >Remove</button>
        </td>
    </tr>
@endforeach

enter image description here enter image description here

CodePudding user response:

First add an input hidden in your existing items. Adapt the name of the input if this doesn't work

<input type="hidden" name="requirements[][id]" value="{{ $reqs->id }}" />

Then check for the presence of the id in your method

foreach ($request->requirements as $key => $requirements) {

    // Update
    if (isset($requirements['id']) && $requirements['id']) {
        $req = FormReq::find($requirements['id']);
        $req->requirements = $requirements['title'];
    // Create
    } else {
        $req = new FormReq();
        $req->requirements = $requirements['title'];
        $req->form_id = $id;
    }
    $req->save();
}
  • Related