CakePHP - Delete a Record


To delete a record in database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to delete.

Call the get() method with this new instance and pass the primary key to find a record which will be saved in another instance. Use the TableRegistry class’s instance to call the delete method to delete record from database.


Make changes in the config/routes.php file as shown in the following code.


   use Cake\Core\Plugin;
   use Cake\Routing\RouteBuilder;
   use Cake\Routing\Router;

   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/users/delete', ['controller' => 'Users', 'action' => 'delete']);

Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.


   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;
   class UsersController extends AppController{
      public function index(){
         $users = TableRegistry::get('users');
         $query = $users->find();
      public function delete($id){
         $users_table = TableRegistry::get('users');
         $users = $users_table->get($id);
         echo "User deleted successfully.";

Just create an empty View file under Users directory called delete.ctp.


Create a directory Users at src/Template, ignore if already created, and under that directory create a View file called index.ctp. Copy the following code in that file.


<a href = "add">Add User</a>

      foreach ($results as $row):
         echo "<tr><td>".$row->id."</td>";
         echo "<td>".$row->username."</td>";
         echo "<td>".$row->password."</td>";
         echo "<td><a href='".$this->Url->build
         (["controller" => "Users","action" => "edit",$row->id])."'>Edit</a></td>";
         echo "<td><a href='".$this->Url->build
         (["controller" => "Users","action" -> "delete",$row->id])."'>Delete</a></td></tr>";

Execute the above example by visiting the following URL and click on Delete link to delete record.



After visiting the above URL and clicking on the Delete link, you will receive the following output where you can delete record.

Delete a Record