Exception or error:
I’m making CRUD example using Laravel and Blade Template. I’m followed WordPress UI. The problem is to delete multiple checkbox based on search typed using same select ALL checkbox
<script>
// SHOW ROW BASED ON SEARCH TYPED
function myFunction() {
const filter = document.querySelector('#myInput').value.toUpperCase();
const trs = document.querySelectorAll('#myTable tr:not(.header)');
trs.forEach(tr => tr.style.display = [...tr.children].find(td => td.innerHTML.toUpperCase().includes(filter)) ? '' : 'none');
}
// SELECT ALL ROW
function checkAll(parent) {
var child = document.getElementsByName('pegawai');
for (var i = 0; i < child.length; i++) {
if (child[i] != parent)
child[i].checked = parent.checked;
}
}
</script>
<div class="card-body">
<a href="/test/admin/pegawai/tambah" class="btn btn-primary">Input Pegawai Baru</a>
<a href="" class="btn btn-danger">Hapus</a>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." class="form-control">
<br/>
<br/>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th><input type="checkbox" onclick="checkAll(this)"></th>
<th>Foto</th>
<th>Nama</th>
<th>Alamat</th>
</tr>
</thead>
<tbody id="myTable">
@foreach($pegawai as $p)
<tr>
<td><input type="checkbox" name="pegawai"></td>
<td><img width="150px" src="{{ url('/data_file/'.$p->file) }}"></td>
<td><a href="/test/admin/pegawai/edit/{{ $p->id }}">{{ $p->nama }}</a></td>
<td>{{ $p->alamat }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
How to solve:
change your input checkbox name to support array and also set value to id
<td><input type="checkbox" name="pegawai[]" value="{{ $p->id }}"></td>
On your controller you can bulk delete as
Pegawai::whereIn('id', $request->pegawai)->delete(); # events wont be fired on model
Or like this as id is primary key
Pegawai::destroy($request->pegawai);
more at https://laravel.com/docs/master/eloquent#deleting-models
Check the display style to use same select all
// SELECT ALL ROW
function checkAll(parent) {
var child = document.getElementsByName('pegawai');
for (var i = 0; i < child.length; i++) {
if ((child[i] != parent) && (child[i].closest('tr').style.display != 'none'))
child[i].checked = parent.checked;
}
}