Search code examples
laravelformseditsql-delete

Laravel, multiple checkbox for delete and button edit in the same view


I have to insert in the same view a edit button and multiple checkboxes to delete records in DB. The edit button works only for the first record, the checkbox delete only for the last even if i check multiple options. The functions works if there is edit button or delete checkboxes alone, not together.

@isset($lista)
<table>
    <th>Lista degli utenti Staff: </th>
    <tr>
        <td> Nome </td>
        <td> Cognome </td>
        <td> Username </td>
        <td> Modifica </td>
        <td> Elimina </td>
        @foreach ($lista as $staff)
        <tr>
        <td>{{$staff->nome}} </td>
        <td> {{$staff->cognome}} </td>
        <td> {{$staff->username}} </td>
        <td>
            {{ Form::open(array( 'route'=> ['modificastaff', $staff->id],'method'=>'post')) }}
            {{ Form::submit('Modifica') }}
            {{ Form::close() }}
        </td>
        <td>
            {{ Form::open(array( 'route'=> ['eliminastaff'],'method'=>'post')) }}
            {{ Form::checkbox('checked[]', $staff->id) }}
        </td>
    </tr>
    @endforeach
{{ Form::submit('Elimina') }}  
{{ Form::close() }}
</table>  
@endisset

Solution

  • Your first form inside the table is fine. You open it, ask for submit and then close it within its loop / <tr>.

    The issue you are having is because you are opening multiple forms for your checkbox and they are not closing within the loop / table. This means you are opening multiple forms on top of each other and on top of the edit form, which is causing the error.

    To fix, change this:

    <td>
            {{ Form::open(array( 'route'=> ['eliminastaff'],'method'=>'post')) }}
            {{ Form::checkbox('checked[]', $staff->id) }}
        </td>
    </tr>
    @endforeach
    {{ Form::submit('Elimina') }}  
    {{ Form::close() }}
    

    to this:

        <td>
            {{ Form::open(array( 'route'=> ['eliminastaff'],'method'=>'post')) }}
            {{ Form::checkbox('checked[]', $staff->id) }}
            {{ Form::submit('Elimina') }}  
            {{ Form::close() }}
        </td>
    </tr>
    @endforeach
    

    If you want to accept multiple checks, you will have to re-architect this a bit. But this will solve your issue for the 1st edit / last delete error you were having.