CakePHP Delete a Record in database

cakephp

To delete a record from a database using CakePHP, you’ll need to create a controller action that uses the CakePHP ORM to retrieve the record and then calls the delete method on the entity.

Here’s an example of how to delete a record in CakePHP:

Controller action:

public function delete($id)
{
    $this->request->allowMethod(['post', 'delete']);
    $post = $this->Posts->get($id);
    if ($this->Posts->delete($post)) {
        $this->Flash->success(__('The post has been deleted.'));
    } else {
        $this->Flash->error(__('The post could not be deleted. Please, try again.'));
    }
    return $this->redirect(['action' => 'index']);
}

View template:

<?= $this->Form->create(null, ['url' => ['action' => 'delete', $post->id]]) ?>
    <?= $this->Form->button(__('Delete')) ?>
<?= $this->Form->end() ?>

In this example, the delete action retrieves the post with the specified id and then calls the delete method on the entity to delete it from the database.

For more information about using the ORM in CakePHP, you can refer to the documentation at https://book.cakephp.org/4/en/orm.html.