</> Code The Pixel

CakePHP 4 Bulk Delete

Asyraf Wahi Anuar - May 17, 2020

Estimated reading time: 2 minutes, 5 seconds

This tutorial will show how to create a bulk delete function in CakePHP 4. The bulk delete is a process of selecting a group of records in a single table and removing it from the database. A checkbox will be rendered on each of the record IDs and sent to the function that manages the delete all process.

Create Checkbox
File Location: ...\templates\Users\index.php
A checkbox is used to capture the id of each selected record that need to be deleted. The checkbox is generated in the index page as shown below:

<table id="main_index" class="table table-hover text-nowrap">
		<th><?= $this->Paginator->sort('#') ?></th>

		...other codes

	<?= $this->Form->create(null,['url'=>['action'=>'bulkDelete']]) ?>
	<?php foreach ($users as $user): ?>
		<td><?= $this->Form->checkbox('ids[]',['value'=>$user->id]) ?></td>
	<button class="button">Delete Selected</button>
	<?= $this->Form->end() ?>
	<?= $this->fetch('postLink'); ?>

Public Function bulk delete
File Location: ...\src\Controller\UsersController.php
Create the public function that handles the bulk delete process as shown below in your controller.

public function bulkDelete()
	$ids = $this->request->getData('ids');
	if($this->Users->bulkDelete(['Users.id IN'=>$ids])){
		$this->Flash->success(__('The selected user has been deleted.'));
	} else {
		$this->Flash->error(__('Please select user to delete'));
		return $this->redirect(['action' => 'index']);

Now you should be able to select and delete the records.

If you want to have a main checkbox in your header that will select  all or deselect all the checkboxes with one single click, use this code in your header:

<th><?= $this->Form->checkbox('ids[]',['onchange'=>'checkAll(this)', 'name'=>'chk[]']) ?></th>

Then add the following script at the end of your code:

 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;

That all. Happy coding :)

Cite this article (APA 6th Edition)

CakePHP 4 Print PDF Using CakePDF
June, 17 2020
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 File Upload Using Proffer Plugin
May, 15 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Sharing Link
Click the icon to share